概念
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
| export function square(x) { return x * x; }
export function cube(x) { return x * x * x; }
|
1 2 3 4 5
| 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
| 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, minimize: true, }, mode: "development", };
|
https://webpack.js.org/guides/tree-shaking/
https://zhuanlan.zhihu.com/p/40052192
https://zhuanlan.zhihu.com/p/32831172