Webpack5 detailed configuration and introduction

The basic concept of webpack:
Weibo pack is a front-end resource construction tool and a static module packer. From the perspective of webpack, all front-end resources will be treated as a module, and it will be statically based on the dependencies of the modules. Analyze, package and generate the corresponding static resources (bundle)
entry: entry instructions, start packaging with which file as the entry point, analyze and build the internal dependency graph
output: output instructions, where the resource bundles packaged by webpack are output, and how Naming
loader: Let Weibo pack handle those non-js files.
plugins: do some more powerful tasks. The scope of plugins includes, from packaging optimization and compression, to redefining the variable
mode in the environment : there are development mode and production mode , The environment that allows the code to run locally in the development mode, the production environment configuration, the environment that can optimize the code to run on the
webpack5
1. Automatically delete node.js polyfills, automatically stop filling these core modules, and focus on modules compatible with the front end (you can Manually add a polyfill for the core module of node.js, the error message will prompt how to achieve this goal)
2. Chunk and module ID, new algorithms for long-term caching have been added, and these functions are enabled by default in the production mode
3. Chunk ID under the
production environment It is necessary to have chunk naming rules
inside webpack 4. Tree Shaking
can handle tree shaking of nested modules
5. Webpack is now able to deal with the relationship between multiple modules
6. Able to tree shaking for commonjs
7. Can generate ES5 and ES6 code
8. Monitor the output files, only the modified files will be updated during the rebuild. This update will find the output files during the first build to see if there are any changes, and then decide whether to output the files

Here are some details of the configuration
1.entry

2.output

output:{ //file name (specified name + directory) filename:'js/[name].js', //output file directory (public directory for all public resources) path:resolve(__dirname,'build') , //All resources introduce a common path prefix-->'imgs/a.jpg' (this is the current directory search) -->'/imgs/a.jpg' (this is the search under the server address, I prefer to use this) publicPath:'/',// (used more in production environments) chunkFilename:'[name]_chunk.js',//The name of the non-entry chunk (import or options) If there is no such, it will be the first To output the directory library:'[name]',//The variable name exposed to the outside of the entire library, the external can be directly imported and used, generally combined with dll plus a separate package of a library, and then introduced and used libraryTarget:'window',/ / The variable name is added to which browser libraryTarget:'global', // The variable name is added to which one node libraryTarget:'commonjs',










},

3.module configuration

module:{ rules:[ {test:/.css KaTeX parse error: Expected'EOF', got'}' at position 81: …','css-loader']} ̲, {… /, //Do not check node_modules The js file under exclude:/node_modules/, //Only check the js file in src include:resolve(__dirname,'src'), //prioritize enforcement :'pre', //delay enforcement //enforce:' post' loader:'eslint-loader'} ] }












4.resolve configuration

//Analysis module rules
resolve:{ //Configuration analysis module path alias: you can abbreviate the path, the disadvantage is that the path does not prompt alias:{ $css:resolve(__dirname,'src/css') }, //The configuration omits the file path Suffix name, so don’t take the same file name, otherwise it will cause problems. extensions:[ '. js ','json','.css' ], //Tell webpack which directory to find for the parsing module, the upper level The upper level find // modules:['node_modules'], //But if you write deeper, it is very inconvenient, you can change the way of writing, directly write the path modules:[resolve(__dirname,'.../... /node_modules'),'node_modules'] }












5.devServer detailed configuration

devServer:{ //The directory where the code is run contenBase:resolve(__dirname,'build'), //Monitor all files in the contentBase directory, once the file changes, it will reload watchContentBase:true, //Some files need to be ignored watchOptions: { ignored:/node_modules/ }, //Enable gzip compression to make the server faster and see the effect faster compress:true, //port number port:5000, //domain name host:'localhost', // Automatically open the browser open:true, //Enable the HMR function hot:true, //Do not start the server log information clientLoLever:'none', //Except for some basic startup information, do not display quiet:true, //If there is an error, do not prompt overlay:true in full screen , //The proxy of the server-->Solve the cross-domain problem of the development environment proxy:{


























//Once the devServer (5000) server receives the request for /api/xxx, it will forward the request to another server (3000)
'/api':{ target: "http://localhost:3000", // send When requesting, the request path is rewritten, and /api/xxx -->/xxx (remove api) pathRewrite:{ '^/api':'' } } } }







6.optimization configuration

const TerserWebpackPlugin = require('terser-webpack-plugin')
need to use
TerserWebpackPlugin under the production environment , compress the packaging of html and css, need to import and write at the top

optimization:{ //Extract common code and package splitChunks:{ chunks:'all', //The following are the default values, as long as the above sentence is enough minSize:30 *1024,//The minimum split chunk is 30kb maxSize:0,//Maximum unlimited minChunks:1,//The chunks to be extracted are quoted at least once maxAsyncRequests:5,//The maximum number of files loaded in parallel when loading on demand maxInitRequests:3,//Entry js file The maximum number of concurrent requests automaticNameDelimiter:'~',//Name connector name: true,//You can use the naming rule cacheGroups:{//The group of split chunks //The node_modules file will be exploded into the chunk of the wendors group-- > vendors~xxx.js //To meet the above rules, such as: the size exceeds 30kb, be quoted at least once vendors:{ test:/[\]node_modules[\/]/, priority:-10 }, default:{ / /The chunk to be extracted is quoted at least 2 times, minChunks:2, //Priority :-20,























//If the current module to be packaged is the same as the previously extracted module, it will be reused instead of repacking the module to solve the problem of repeated packaging
reuseExistingChunk: true

        }
        }


    },
    runtimeChunk:{
        //将当前模块记录其他模块的hash值单独打包成一个文件runtime,能够保证其他文件的持久化,否则会导致缓存失效
        //main.js文件里面不再储存这个hash值,而是另外一个文件runtime存储,这样当文件改变的时候,main文件也不会被改变
        name:entrypoint => 'runtime-${entrypoint.name}'
    },
    minizer:{
        //配置生产环境的压缩方案,js和css
        [new TerserWebpackPlugin({ //开启缓存
            cache:true,
            //开启多进程打包
            parallel:true,
            //启动sourse-map,否则会被压缩掉
            sourceMap:true
        })]


    }
}

Guess you like

Origin blog.csdn.net/qq_44073682/article/details/115166459