What is thetree-shaking

Tree-shaking is a Dead Code Elimination technology that statically analyzes the imports and exports between modules during packaging, determines which module exports are not being used, and removes them, thus optimizing packaging products.

tree-shakingCan be implemented on a basis

In the previous CommonJs, AMD, CMD modular solution, import and export is highly dynamic and unpredictable, so in the packaging phase, it is impossible to analyze which modules are used, for example:

if(someTrue){
  require('./bar');
  exports.foo = 'foo';
}
Copy the code

In the ES Module solution, the dependency between modules is highly determined and independent of the running state. Therefore, it is possible to analyze ESM modules at compile time and infer which modules are not used from the code literal. This is a necessary condition for tree-shaking implementation.

tree-shakingExamples of action of

As you can see in the example, bar foo is exported from bar.js, whereas only bar is used in index.js, foo is never used, and after tree-shaking, the foo variable is removed as garbage code.

// index.js
import {bar} from './bar';
console.log(bar);

// bar.js
export const bar = 'bar';
export const foo = 'foo';
Copy the code

The webpacktree-shakingImplementation steps

Webpack first marks out which module exported values are not used, and then uses Terser to remove the unused ones.

Specific process:

  • In the make phase, collect module exports and record them in the module dependency graph variable, ModuleGraph
  • The Seal phase traverses the ModuleGraph to mark exports that have not been used.
  • In the product generation phase, the marked export statements are deleted.

The unused Harmony export XXX flag is used for webpack. Look at the picture:

Best practices in Webpack

Although Webpack has been supporting tree-shaking natively since 2.x, due to the dynamic nature of JS, even 5.0 has not solved the problem of code side effects, making the optimization effect not as perfect as expected. Therefore, developers need to consciously optimize the code structure. To help WebPack detect invalid code more accurately.

  1. Avoid meaningless assignments
  2. use#pureAnnotate pure function calls
  3. Disable Bebal translation module import/export statements: Bebal can convert ESM style modules to CommonJs style, Webpack cannot convert CommonJs style modulestree-shaking
  4. Optimize the granularity of exported values:export defaultThe value of, for example:
export default {
    bar: 'bar',
    foo: 'foo'
}
Copy the code

Should be changed to:

const bar = 'bar'
const foo = 'foo'

export {
    bar,
    foo
}
Copy the code
  1. Use the supporttree-shakingPackage, such as usinglodash-esalternativelodash

Webpack opentree-shakingThe configuration of the

In Webpack, three conditions must be met to start the Tree Shaking function:

  • Write module code using ESM specifications
  • Webpack configurationoptimization.usedExportsfortrueTo enable the tag function.
  • The code optimization function can be enabled in one of the following ways:
    1. configurationmode = production
    2. configurationoptimization.minimize = true
    3. provideoptimization.minimizerAn array of

    Such as:

    // webpack.config.js
      module.exports = {
        entry: "./src/index",
        mode: "production",
        devtool: false,
        optimization: {
          usedExports: true,
        },
      };
    Copy the code