Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello, I’m Shanyue.

This is my front end engineering knowledge card collection 11/36 published in Nuggets


Tree Shaking ‘means doing static analysis based on ES Modules and removing functions that are not needed through the AST to reduce packaging volume.

As evidenced by the following examples:

The following example can be demonstrated online in the Rollup Repl

/* TREE-SHAKING */
import { sum } from './maths.js'

console.log( sum( 5.5))/ / 10
Copy the code
// maths.js

export function sum ( x, y ) {
  return x + y
}

// Since the sub function is not referenced, it will not be packaged eventually
export function sub ( x, y ) {
  return x - y
}
Copy the code

In the final packaging process, sub is not referenced and will not be packaged. Here is the packaged code.

// maths.js

function sum ( x, y ) {
  return x + y
}

/* TREE-SHAKING */

console.log( sum( 5.5))Copy the code

import *

Tree Shaking still works when the syntax import * is used.

import * as maths from './maths'

// Tree Shaking still works
maths.sum(3.4)
maths['sum'] (3.4)
Copy the code

Import * as MATHS, the data structure of MATHS is fixed without complex data, and the reference relationship can be found through AST analysis.

const maths = {
  sum () {},
  sub () {}
}
Copy the code

JSON TreeShaking

Tree Shaking even optimizes JSON. The principle is that the JSON format is simple and the AST makes it easy to predict results, unlike JS objects, which have complex types and side effects.

{
  "a": 3."b": 4
}
Copy the code
import obj from './main.json'

// obj.b will still not be packaged because it is not used
console.log(obj.a)
Copy the code

Introducing a Package that supports Tree Shaking

In order to reduce the size of the production environment, we can use some packages that support ES, such as lodash-es instead of LoDash.

We can see if a library supports Tree Shaking in npm.devtool.tech.