tree shaking主要是将import/export
中未引用到的代码给找出来。
通过demo看tree shaking 给我们做了什么
.
├── dist
├── node_modules
├── package-lock.json
├── package.json
├── src
└── webpack.config.js
demo结构
// webpack.config.js
const path = require('path')
module.exports = {
entry: {
app: './src/index.js'
},
mode: 'development',
devtool: 'source-map',
output: {
filename: '[name]-bundle.js',
path: path.resolve(__dirname, 'dist'),
},
optimization: {
usedExports: true,
},
plugins: [
]
}
// src/index.js
import { cube } from './math.js';
cube(5)
// src/math.js
export function square(x) {
return x * x;
}
export function cube(x) {
return x * x * x;
}
// package.json
"sideEffects": false, // 设置有其他作用/副作用的文件地
demo中我们在index.js
中引用了math.js
中的cube
方法,没有引用square
方法,通过tree shaking我们将从未使用的代码找出来。
编译后看app-bundle.js
中的内容
// app.bundle.js 部分打包代码
/***/ "./src/math.js":
/*!*********************!*\
!*** ./src/math.js ***!
\*********************/
/*! exports provided: square, cube */
/*! exports used: cube */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export square */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cube; });
function square(x) {
console.log(123);
return x * x;
}
function cube(x) {
console.log(123);
return x * x * x;
}
以上代码中/*! exports used: cube */
提示使用了cube方法,未使用/* unused harmony export square */
square方法,这是这些配置的作用。既然我们找出了未使用的代码,我们应该删除多余的代码,优化打包后的项目体积。
// webpack.config.js
optimization: {
usedExports: true,
minimize: true, // webpack 4中UglifyjsWebpackPlugin可以通过minimize设置
}
这样我们在开发模式下进行了压缩打包,打包后的square
方法被删除。
生产模式下,我们可以不必加以上代码。