This is the 28th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
What is tree shaking?
We can compare our projects to a tree, and every third party module or function used in the tree can be likened to a green leaf. However, there are many modules or functions that are not used in our projects. These are the leaves that need to be shaken off.
How to start Tree Shaking?
Start Tree Shaking automatically if the following two conditions are met.
- You must use ES6 modularity.
- Start the Production environment.
If you want to tree shaking all your code, you need to do the following configuration in package.json.
- package.json
"sideEffects": ["*.css"]
Copy the code
Set up multiple entry files in Webpack
- Assign values to each entry in the form of an object
entry: {
main: './src/js/index.js'.test: './src/js/test.js'
}
Copy the code
- Give output the file name of the output to make it easier to distinguish.
output: {
filename: 'js/[name].[contenthash:10].js'.path: resolve(__dirname, 'build')}Copy the code
Set common modules to be packaged only once
For example, if A file and B file reference Jquery, the Jquery module will be packaged twice without using the following configuration. However, the following configuration allows you to pack only once. (In the case of multiple entrances)
optimization: {
splitChunks: {
chunks: 'all'}}Copy the code
A file is packaged separately into a chunk through JS code
This usage applies to single-entry files. Just where it is used, through the following way of use.
import(/* webpackChunkName: 'test' */'./test')
.then(({ mul, count }) = > {
// eslint-disable-next-line
console.log(mul(2.5));
})
.catch(() = > {
// eslint-disable-next-line
console.log('File loading error');
})
Copy the code
The complete code is given below to facilitate your understanding.
function sum(. args) {
return args.reduce((p, c) = > p + c, 0);
}
import(/* webpackChunkName: 'test' */'./test')
.then(({ mul, count }) = > {
// eslint-disable-next-line
console.log(mul(2.5));
})
.catch(() = > {
// eslint-disable-next-line
console.log('File loading error');
})
// eslint-disable-next-line
console.log(mul(2.3));
// eslint-disable-next-line
console.log(sum(1.2.3.4));
Copy the code