Code split: separates the code into different bundles, and then loads these files as needed. Without code splitting, all JS code contents are packed into one file, which is very large and affects the loading speed.
Three ways to split code
1. Multiple entry
Multiple entries: With multiple entries, the final output has multiple bundles for multiple pages
Configure multiple entries in entry of webpack.config.js
Entry: {/ / the main entrance to the configuration: '. / SRC/js/index. Js', test: 'the. / SRC/js/test. Js'}, the output: {/ / [name] : Take the file name The main entry name | test output package name of the file filename: 'js / [name]. [10] contenthash: js', path: resolve (__dirname,' built ')},Copy the code
2.optimization
The optimization configuration in Webpack can also package the node_modules code into a single chunk of final output. If it is a multi-entry chunk, it can automatically analyze whether there are any common files in the multi-entry chunk. If there is, it will be packaged into a single chunk
optimization:
-
Node_modules can be packaged as a separate chunk of final output
-
Automatic analysis of multi-entry chunks, whether there are common files (files can not be too small). If there is, it will be packaged into a single chunk
Webpack. Config. Js configuration
optimization: {
splitChunks: {
chunks: 'all'
}
},
Copy the code
Single entry
Multiple entry
3. Through THE JS code
A chunk import dynamic import syntax allows a file to be packaged separately by using JS code
src/js//index.js
import(/* webpackChunkName: 'test' * '/ test'), then (({count} the mul,) = > {/ / file loading success / / eslint - disable - next - line console. The log (the mul (2, 3)); // eslint-disable-next-line console.log(count(2, 4)); }).catch(() => {// eslint-disable-next-line console.log(' file failed to load '); });Copy the code
The demo address
Reference video: B station is still silicon Valley