webpack 之 Tree Shaking

(1) Background

In our code, although some code is written, but not called or executed, for example, a function or module is defined, but it is not introduced or called. At this time, we hope that the module and function that have not been introduced or called Don't be packaged by webpack, this can save packaging time and memory. Tree Shaking means to shake the tree. When shaking the tree, some useless leaves are taken down. This is the meaning of Tree Shaking

Note: Tree Shaking can only be used in ES Module, that is, it only supports the introduction of import modules, and the introduction of require does not apply

(Two) Tree Shaking configuration

First write a small example:

number.js:

function number () {
  var count = 0
  var dom = document.createElement('div')
  dom.innerHTML = count
  dom.onclick = function () {
    count++
    dom.innerHTML = count
  }
  document.body.appendChild(dom)
}

function add (a, b) {
  return a + b
}

export {
  number,
  add
}

index.js:

import { number } from './number'
number()

It can be seen that only the number method is used, and the add method is not used. At this time, npx webpack is packaged, and you can see this part of the file 

Next, use Tree Shaking to package, first configure Tree Shaking

First configure the mode mode, and then write the following code at the same level as the plugins:

optimization: {
    usedExports: true
  }

Indicates that Tree Shaking is used for modules exported everywhere, and then configured in package.json. This configuration item means which does not require Tree Shaking

"sideEffects": false,

Pack npx webpack again, you will find the packed file, add a line

When the mode is the development environment, the packaged file will mark which methods/modules are used, and the unused modules will still be packaged to facilitate debugging in the development environment.

(2) Production environment

Only two places can be configured in the production environment

First: in webpack.config.js

mode: 'production',

In package.json: For example, css does not require Tree Shaking

"sideEffects": [
    "*.css"
  ],

After the two steps are completed, you can pack it again. You can see that there is only the number function, not the add function.

to sum up:

(1) When the mode is the development environment, the packaged file will mark which methods/modules are used, and the unused modules will still be packaged to facilitate debugging in the development environment.

(2) When the mode is the production environment, you only need to configure "sideEffects" in package.json, and other configuration production environments are automatically configured without manual configuration

Guess you like

Origin blog.csdn.net/Luckyzhoufangbing/article/details/108894424