Open kangyana opened 1 year ago
Tree Shaking 指基于 ES Module 进行静态分析,通过 AST 将用不到的函数进行移除,从而减小打包体积。
Tree Shaking
有例为证:
/* TREE-SHAKING */ import { sum } from "./maths.js"; console.log(sum(5, 5)); // 10
maths.js
export function sum(x, y) { return x + y; } // 由于 sub 函数没有引用到,最终将不会对它进行打包 export function sub(x, y) { return x - y; }
最终打包过程中,sub 没有被引用到,将不会对它进行打包。以下为打包后代码:
sub
// maths.js function sum(x, y) { return x + y; } /* TREE-SHAKING */ console.log(sum(5, 5));
当使用语法 import * 时,Tree Shaking 依然生效。
import *
import * as maths from "./maths"; // Tree Shaking 依然生效 maths.sum(3, 4); maths["sum"](3, 4);
import * as maths,其中 maths 的数据结构是固定的,无复杂数据,通过 AST 分析可查知其引用关系。
import * as maths
maths
const maths = { sum() {}, sub() {}, };
Tree Shaking 甚至可对 JSON 进行优化。 原理是因为 JSON 格式简单,通过 AST 容易预测结果,不像 JS 对象有复杂的类型与副作用。 main.json
{ "a": 3, "b": 4 }
import obj from "./main.json"; // obj.b 由于未使用到,仍旧不会被打包 console.log(obj.a);
为了减小生产环境体积,我们可以使用一些支持 ES 的 package,比如使用 lodash-es 替代 lodash。
lodash-es
lodash
我们可以在 npm.devtool.tech (opens new window)中查看某个库是否支持 Tree Shaking。
Tree Shaking
指基于 ES Module 进行静态分析,通过 AST 将用不到的函数进行移除,从而减小打包体积。有例为证:
maths.js
最终打包过程中,
sub
没有被引用到,将不会对它进行打包。以下为打包后代码:1. import *
当使用语法
import *
时,Tree Shaking 依然生效。import * as maths
,其中maths
的数据结构是固定的,无复杂数据,通过 AST 分析可查知其引用关系。2. JSON TreeShaking
Tree Shaking 甚至可对 JSON 进行优化。 原理是因为 JSON 格式简单,通过 AST 容易预测结果,不像 JS 对象有复杂的类型与副作用。 main.json
3. 引入支持 Tree Shaking 的 Package
为了减小生产环境体积,我们可以使用一些支持 ES 的 package,比如使用
lodash-es
替代lodash
。我们可以在 npm.devtool.tech (opens new window)中查看某个库是否支持 Tree Shaking。