webpack tree shaking

概念

tree shaking 用于移除 js 上下文中未引用的代码。

tree shaking 依赖于 es6 模块语法( import 、 export)的静态结构特性。

使用方法

1、使用 es6 模块语法(即 import export)

2、确保没有 compiler 将 ES2015 模块语法转换为 CommonJS 模块

3、在项目 package.json 文件中,添加一个 “sideEffects” 属性

4、通过将 mode 选项设置为 production,启用 minification(代码压缩) 和 tree shaking。

示例

1
2
3
4
5
6
7
8
9
// math.js
export function square(x) {
return x * x;
}

export function cube(x) {
return x * x * x;
}

1
2
3
4
5
//index.js
import { cube } from "./math";

console.log(cube(2));

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
entry: {
main: path.resolve(__dirname, "src/js/index.js"),
},
output: {
filename: "./js/[name].[contenthash:5].js",
path: path.resolve(__dirname, "dist"),
},
plugins: [new HtmlWebpackPlugin()],
optimization: {
usedExports: true, // 会用注释标记哪些导出被使用了,一些优化代码的插件会使用此注释进行 treeshaking
minimize: true, //设置为 true 时,webpack 会使用 TerserPlugin 压缩 bundle,会删除 usedExports 标记的未使用导出
},
mode: "development", // 设置成 production 时,会默认设置 usedExports 和 minimize 为 true
};

https://webpack.js.org/guides/tree-shaking/

https://zhuanlan.zhihu.com/p/40052192

https://zhuanlan.zhihu.com/p/32831172