Tree Shaking

Tree Shaking can be used to weed out dead code that doesn’t work in JavaScript. It relies on static ES6 modularity syntax, such as importing and exporting through import and export. Tree Shaking first appeared in Rollup and was introduced in Webpack 2.0.

And just to visualize it, let’s do a concrete example. If you have a file util. Js that contains many utility functions and constants, import and use util. Js in main.js as follows: util.

Util. Js source code:

export function funcA() {}export function funB() {}export const a = 'a';
Copy the code

The main. Js source code:

import {funcA} from './util.js';
funcA();
Copy the code

Tree Shaking util.js

export function funcA() {}Copy the code

Because only funcA is used in util.js, the rest is removed as dead code by Tree Shaking.

Note that for Tree Shaking to work, JavaScript code given to Webpack must be in ES6 modularity, because ES6 modularity is static (paths in import and export statements must be static strings, And cannot be placed in other code blocks), which allows Webpack to simply analyze which exports have been imported. If you use modularity in ES5, such as module.export={… }, require(x+y), if(x){require(‘./util’)}, Webpack can’t figure out which code to cull.

Currently, Tree Shaking has some limitations. Experiments show that:

  1. Do not Tree Shaking entry files.
  2. Don’t Tree Shaking asynchronously partitioned code.