原创翻译,转载请注明出处。
原文地址:https://webpack.js.org/guides/tree-shaking/
Tree shaking是一个术语,通常用于JavaScript的上下文来消除没有作用的代码,或者精确讲,保留有用代码。它依赖于ES2015中针对于其模块系统里静态构造的引入/导出。它的名字和概念由ES2015模块打包器rollup而广为人知。
Webpack2对ES2015模块提供了一个内置的支持,用来检测对未使用模块的导出。
例子
假设一个maths.js库文件导出两个函数,square和cube:
// This function isn't used anywhere
exportfunctionsquare(x){
return x * x;
}
// This function gets included
exportfunctioncube(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并没有被导出。
/* ... 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
functionsquare(x){
return x * x;
}
// This function gets included
functioncube(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在编译中没有被保留。
/* ... */
function(e,t,n){"use strict";functionr(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))}
链接
Tree shaking with webpack 2, TypeScript and Babel
Tree-shaking with webpack 2 and Babel 6
webpack 2 Tree Shaking Configuration
-- End --
Webpack树摇技术解析
本文介绍Webpack中的Tree Shaking技术,该技术通过ES2015模块系统的静态引入/导出特性来消除未使用的代码。文章通过具体示例展示了如何在实际项目中应用此技术,以减少最终构建文件的大小。
1044

被折叠的 条评论
为什么被折叠?



