Webpack packs nodejs backend environment

It's best not to use any webpack to package nodejs applications, it's too stupid, please refer to the latest write-up for details


Many examples of webpack are used in the front-end, and it is difficult for Baidu to find a decent back-end packaging tutorial. Let’s summarize it from Google and the official webpack documentation.

getting Started

First prepare an main.jsentry file

import request from './request'
import cherrio from './query'

request('https://www.baidu.com/s?ie=UTF-8&wd=axios').then(res=>{
    
    
    var $ = cherrio(res)
    var rs = $([
        {
    
    
            test:'.c-container',
            attr:'srcid'
        }
    ])
    console.log(JSON.stringify(rs))
})

The above code is just a simple crawler balabala, which uses the es6 import keyword that is not currently supported by the nodejs environment.

Then we are using webpack api to write a webpack.jswebpack configuration file

var webpack = require('webpack')
webpack({
    
    
    mode: "development",
    entry: './main.js',
    output: {
    
    
        filename: 'bundle.js',
        path: __dirname
    },
    target: 'node' // 这是最关键的
}, (err, stats) => {
    
    
    if (err) {
    
    
        console.log('err:', err)
    }
})

The target configuration item is the target environment for packaging, and the default is the browser environment. Adding this can directly package js in the nodejs environment

compression optimization

But this is not over, the packaged one bundle.jsbecomes very large, even if all your own js files are very small,
insert image description here
then you need to use the externals of webpack

Brief summary

This externals configuration item was originally for the front-end CDN to introduce js and optimize the size of bundle.js , for example

webpack({
    
    
    //...
    externals:{
    
    
        axios:"axios"
    }
}

The axios module in the package bundle.jsis only such a point, not all the axios modules are imported, and the axios in it is the global axios, which realizes the function of CDN importing js
insert image description here

practical use

The official recommends the webpack-node-externals plugin in the externas configuration item, but it has no effect in actual use. The packaged size is still 1.46MB, and no problems can be found.

Using the simple and general features to write a piece of js

var package = require('package.json'),
	webpack = require('webpack')

var externals = {
    
    },
    pends = Object.assign(package.dependencies,package.devDependencies)
for(let i in pends){
    
    
    externals[i] = `require('${
      
      i}')`
}
webpack({
    
    
    //...
    externals
}

It can be clearly seen bundle.jsthat it has become super small.
insert image description here

debugger

If you need dubgger, you need to use the devtools configuration item

webpack({
    
    
	//...
    mode: "development",
    target: 'node',
    devtool: 'source-map'
})

Then in vscode, if you recommend this configuration, you can locate this bundle.jsfile and you can debugger

{
    
    
    "version": "0.2.0",
    "configurations": [
        {
    
    
            "type": "node",
            "request": "launch",
            "name": "node 文件",
            "program": "${file}",
            "skipFiles": [
                "<node_internals>/**"
            ],
        }
     ]
}

The only downside is that there is currently no vscode + sourcemap that uses the native breakpoint function debugger. There are two current solutions

1. Add a debugger to the code
2. Use vscode breakpoints when running to the debugger, and these breakpoints will be retained when the debugger is run next time


2020-5-24 12:14 update, finally found out how vscode uses the native breakpoint function

Since my webpack is packaged bundle.jsin the subdirectory utils , the configuration of vscode is

{
    
    
       "type": "node",
       "request": "launch",
       "name": "webpack后端测试",
       "program": "${workspaceFolder}/utils/bundle.js",
       "sourceMapPathOverrides": {
    
    
           "webpack:///./~/*": "${workspaceRoot}/node_modules/*",
           "webpack:///./*": "${workspaceRoot}/utils/*",
           "webpack:///*": "*"
       }
}

The webpack:///./* in sourceMapPathOverrides is the key configuration item, and the breakpoint function of vscode can be realized by adding the directorybundle.js where it is located

Guess you like

Origin blog.csdn.net/qq_41535611/article/details/106311647