[Translation] webpack official website documentation: guide -- 24.Tree Shaking

Original translation, please indicate the source when reprinting.

Original address: https://webpack.js.org/guides/tree-shaking/

 

Tree shaking is a term commonly used in the context of JavaScript to eliminate non-functional code, or more precisely, keep useful code. It relies on ES2015 imports / exports for static constructs in its module system . Its name and concept are made known by the ES2015 module bundler rollup .

Webpack2 provides a built-in support for ES2015 modules to detect exports of unused modules.

 

example

Suppose a maths.js library file exports two functions, square and cube :

 

// This function isn't used anywhere
exportfunctionsquare(x){
    return x * x;
}
 
// This function gets included
exportfunctioncube(x){
    return x * x * x;
}

 

 

In our main.js we just import cube :

 

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

 

 

Run node_modules/.bin/webpack main.js dist.js and check dist.js to see that square is not exported.

 

/ * ... 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
 
/***/})

 

When running a production build running node_modules/.bin/webpack --optimize-minimize main.js dist.min.js , there is only a minified version of cube , and square is not preserved in the build.

 

/* ... */
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))}

 

Link

Tree shaking with webpack 2, TypeScript and Babel

Tree-shaking with webpack 2 and Babel 6

webpack 2 Tree Shaking Configuration

 

-- End --

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326885259&siteId=291194637