参考 webpack 官网
是什么
tree-shaking 就是让没有用到的 JS 代码不打包,以减小包的体积。
使用方法
怎么删
tree-shaking 是通过 ES6 语法 ES Module 语法 import 和 export 关键字去判断。
CommonJS 语法(即 require 和 module.exports 语法)是无法 tree-shaking 的。
例子:
比如说我们有两个文件 1.js 和 2.js 。
- 1.js
export a = 1
export b = 2
export c = 3
- 2.js
import { a } from '1.js';
这时 1.js 中的 变量 b 和 c 就没有用到,webpack 就不会去打包 b 和 c 的代码
不推荐这样引用:
import _ from 'lodsh'
这样会导致无法 tree-shaking 无用模块
引用时推荐按需引入,只引入需要的模块。
怎么不删
可以在 package.json 中配置 sideEffects,防止某些文件被删掉
{
"name": "your-project",
"sideEffects": ["./src/some-side-effectful-file.js"]
}
sideEffects 可以将文件标记为 side-effect-free 即将文件标记为副作用,用于标记文件是否需要 tree-shaking
比如:
- import 了 x.js,而 x.js 只是添加了 window.x 属性,那么 x.js 就要放到 sideEffects 里
- 所有被 import 的 CSS 都要放在 sideEffects 里
怎么开启
只需在 webpack config 中将 mode 设置为 production 即可(开发环境没必要 tree-shaking)