[译]webpack官网文档 :指南 -- 24.Tree Shaking

原创翻译,转载请注明出处。

原文地址:https://webpack.js.org/guides/tree-shaking/

 

Tree shaking是一个术语,通常用于JavaScript的上下文来消除没有作用的代码,或者精确讲,保留有用代码。它依赖于ES2015中针对于其模块系统里静态构造的引入/导出。它的名字和概念由ES2015模块打包器rollup而广为人知。

Webpack2ES2015模块提供了一个内置的支持,用来检测对未使用模块的导出。

 

例子

假设一个maths.js库文件导出两个函数,squarecube

 

// 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 --

猜你喜欢

转载自stef.iteye.com/blog/2370984