What is Tree Shaking

Tree shaking, as the name suggests, is shaking a tree so that its dead leaves fall. In a program, it is used to remove unused code from the program.

For example:

// index.js import {a} from './ 'utils.js; // export function a() {//... } export function b() {//... }Copy the code

What Tree Shaking does is remove the B method when packaging

Conditions for being able to be shaken by tree

  1. Can be statically analyzed
    1. ESM: Currently, only ESM is known to be a declaration in the module definition. Other AMD and CJS modules are all expressions and cannot be statically analyzed
    2. Export: Expressions generated by non-expressions depend on the runtime, so WebPack cannot determine if they contain side effects and will not remove them for security reasons
  2. Unused code
  3. Code with no side effects: Code with side effects, such as changes to the prototype chain, may be inherited elsewhere in the project and cannot be removed
// index.js import {Button} from './ 'utils.js; // utils.js function Button(_ref) {} function withAppProvider() {//... } const Button1 = withAppProvider(Button); export { Button, Button1, };Copy the code

Where Button1 is the result of a call to the withAppProvider function, it is not known at run time whether the process of calling withAppProvider caused any side effects.

With this run-time dependent approach, webPack has no way of determining if there are side effects, so it will not be removed for security reasons.

But the developer knows if this code has sideEffects, and can manually flag sideEffects to tell webpack which modules need to keep sideEffects, so webpack can safely remove unused code from the remaining modules.

How to configure it in a project

Enable mode: production in the production environment

When mode: Production is enabled, TerserPlugin is enabled by default, and tree Shaking is enabled by default

Note: Babel needs to be upgraded above Babel 7. Older versions of Babel compile to non-ESM modules, but Babel-Loader executes Webpack first and then packaging, which makes it impossible for Webpack to tree shaking the code. The new Version of Babel solves this problem by printing the code as an ESM

Configuration sideEffects

  1. The CSS file
  2. A file that contains global variables
  3. Other files containing the desired side effects

Component library

Webpack packs output modules as IIFE. If a component library is packaged as non-ESM in WebPack and then introduced by a third party, then the component library cannot be seen as tree shaking when packaged in a third party project

The solution

  1. Separate exports: Like Lodash, you package each method into a separate file and import it as needed, but you can’t import multiple methods at once
  2. Use Rollup to package the ESM