Author: afterrhyme of

Tree Shaking

What is Tree Shaking

Indicates that only the code in the required module is imported, not used is not packaged

import { add } from './math.js';
add(1, 2);
Copy the code

Math.js has two methods, and if you use Tree Shaking only add methods are packaged

2. How to configure it

The webpack.prod.js production environment does not need to configure this, and even if it did, it would be useless.

Optimization: {// Use tree shaking usedExports: true}Copy the code

package.json

"sideEffects": false.// Use tree shaking for all modules
"sideEffects": ["@babel/polly-fill"."*.css"] // Exclude @babel/polly-fill, exclude all CSS files and import modules using tree shaking
Copy the code

Note that development tree shaking will not work because if you are debugging, sourceMap line count will not be correct and production will work

Production Development

1. How to switch webPack configuration between development environment and production environment

  • Create the production environment file./build/webpack.prod.js
  • Create the development environment file./build/webpack.dev.js
  • Create a public code file. / build/webpack.com mon. Js

Merge configuration files using the plug-in webpack-merge

2. Configure the package command

package.json

"Scripts ": {"dev": "webpack-dev-server --config./build/webpack.dev.js", // start hot update, select dev config file "build": "Webpack --config./build/webpack.prod.js"Copy the code

Code Splitting

Why do we do code splitting? Let me give you an example.

Suppose we introduce a LoDash third-party library that is 1MB in size and our business code is 1MB. At this point, no processing is done and a main.js package is generated with a size of 2MB. The user needs to request a 2MB main.js file to open the browser.

import _ from "lodash"; / / suppose lodash have 1 MB / / suppose business code have 1 MB console. The log (_. Join ([' a ', 'a', 'c'], "-")) to the console. The log (_. Join ([' a ', 'b', 'c'], "-"))Copy the code

At this point we modify the business code

import _ from "lodash"; / / suppose lodash have 1 MB / / suppose business code have 1 MB console. The log (_. Join ([' a ', 'XXXXX', 'c'], "-")) to the console. The log (_. Join ([' a ', 'b', 'c'], "-"))Copy the code

Repackage to generate main.js 2MB. The user needs to re-pull the 2MB code file. This leads to slow load times and poor performance.

So what’s a good way to solve this problem?

The first method is synchronous

Import _ from "lodash" // Assume lodash has 1MB window._ = _Copy the code
/ / assume business code have 1 MB console. The log (_. Join ([' a ', 'd', 'c'], "-")) to the console. The log (_. Join ([' a ', 'b', 'c'], "-"))Copy the code

webpack.config.js

entry: {
  lodash: './src/lodash.js',
  main: './src/index.js'
}
Copy the code
  • When the page is first accessed, main.js is loaded: it is split into vendor~lodash.js 1MB and business code main.js 1MB
  • After modifying the business code, the user does not need to reload the Vendor ~ LoDash code. Just reload main.js

Advantages: It can effectively improve the speed of code running, improve user experience, and improve performance. Disadvantages: It is not intelligent to manually split the page code

The second method is synchronous

webpack.config.js

optimization:{
	  splitChunks:{
	    chunks:'all'
    }
}
Copy the code
import _ from "lodash"; / / suppose there is 1 MB console. The log (_. Join ([' a ', 'd', 'c'], "-")) / / is omitted 100000 lines of business logic to the console. The log (_. Join ([' a ', 'b', 'c'], "-"))Copy the code

Advantages: Can be split automatically compared to the second method, and can be packaged to introduce main.js and vendors~main.js

The third way is asynchronous

Installing a plug-in

yarn add -D babel-plugin-dynamic-import-webpack
Copy the code

.babelrc

"plugins": ["babel-plugin-dynamic-import-webpack"]
Copy the code

The asynchronous code is as follows

function getComponent(){
  return import('lodash').then(({default:_})=>{
    let element = document.createElement('span')
    element.innerHTML = _.join(['x','y'],'-');
    return element;
  })
}

getComponent().then(ele=>{
  document.body.appendChild(ele)
})
Copy the code

Note: Modules imported by the asynchronous code import are automatically imported without the need to configure additional webpack.config.js

SplitChunksPlugin Details of configuration parameters

1, webpackChunkName

Change the name of the file packaged by the third party

Install official dependencies

npm install --save-dev @babel/plugin-syntax-dynamic-import
Copy the code

.babelrc

"plugins": ["@babel/plugin-syntax-dynamic-import"]
Copy the code

Add the name /_ webpackChunkName:” loDash “_/ to the project code

function getComponent(){
  return import(/* webpackChunkName:"lodash" */'lodash').then(({default:_})=>{
    let element = document.createElement('span')
    element.innerHTML = _.join(['x','y'],'-');
    return element;
  })
}

getComponent().then(ele=>{
  document.body.appendChild(ele)
})
Copy the code

Note: the generated code files are./dist/vendors~lodash.js

If the generated code file does not want to add vendors~, it goes directly to lodash.js

Then configure webpack.config.js

Optimization :{splitChunks:{chunks:'all', cacheGroups:{// Indicate whether packaged files should carry vendors, whether synchronous or asynchronous vendors:false, default:false } } }Copy the code

2. Detailed parameter functions of splitChunks

optimization: { splitChunks: { chunks: 'all', // async means only asynchronous code is partied, and initial means only synchronous code is partied, so all are both going to cacheGroups. Vendors minSize: MaxSize: 50000, // If the size of the code to be split is greater than 50000, it will be split twice, usually with fewer minChunks: MaxAsyncRequests: 3 maxAsyncRequests: 3 maxAsyncRequests: 3 maxAsyncRequests: 3 maxAsyncRequests: 3 maxInitialRequests: 3,// Sets the entire site home or entry file to no more than three automaticNameDelimiter: '~', and vendors~main.js name: CacheGroups: {vendors: {test: vendors: vendors: /[\\/]node_modules[\\/]/, // If it is in node_modules, then it is packaged to vendors. Js priority: Filename :'vendors. Js' // Indicates that all third parties are packaged into a file called vendor.js}, default: {// If you want to introduce modules that you have written in your project, start with the chunks, non-node_modules // minChunks: 2, priority: -20,// the larger the value is, the higher the priority is. True, // If the code has already been packaged, it will not be split and packaged for repeated references, but will be reused. filename: 'common.js' } } } },Copy the code

Notice here

  • If synchronous code is introduced, it will not be split immediately, but will go to cacheGroups and split as the case may be

portal

Webpack common configuration Series 1