Tree Shaking

Tree shaking 是一个常用术语,是指消除JavaScript上下文中无用代码,或更精确地说,只导入有用的代码。它依赖于ES6模块import/export 模块系统的静态结构(static structure)。名称和概念已经被ES6模块打包工具rollup普及。

webpack 2 内置支持对ES6模块(别名harmony modules)以及未使用的模块的导出检测。

示例

考虑一个 maths.js 库文件导出两个函数,squarecube

// 这个函数不在任何地方被使用
export function square(x) {
    return x * x; //平方
}

// 这个函数被其他脚本使用
export function cube(x) {
    return x * x * x; //立方
}

在我们的 main.js 中,我们选择性地导入 cube

import {cube} from './maths.js';
console.log(cube(5)); // 125

运行 node_modules/.bin/webpack main.js dist.js 并检查 dist.js 显示没有导出square(请查看 "unused harmony export square"的注释)(愚人码头注:查看/* harmony export (immutable) */ __webpack_exports__["a"] = cube;这条语句,显示这里只导出了cube):

/* ... webpackBootstrap ... */
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export square */
/* harmony export (immutable) */ __webpack_exports__["a"] = cube;
// This function isn't used anywhere
function square(x) {
  return x * x;
}

// This function gets included
function cube(x) {
  return x * x * x;
}

/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__maths_js__ = __webpack_require__(0);

console.log(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__maths_js__["a" /* cube */])(5)); // 125

/***/ })

当运行生产环境构建node_modules/.bin/webpack --optimize-minimize main.js dist.min.js时,只保留了 cube 的压缩版本,而 square 并没有保留在构建的 bundle 中:

/* ... */
function(e,t,n){"use strict";function r(e){return e*e*e}t.a=r}
/* ... */
function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(0);console.log(n.i(r.a)(5))}

results matching ""

    No results matching ""