生产环境
- 生产环境下,webpack会自动开启tree-shaking
其他环境
- 其他环境下模拟tree-shaking
module.exports = {mode: 'none'entry: './main.js'output: {filename: 'bundle.js'},optimization: { // 优化项,tree shaking的具体实现usedExports: true, // 只打包有引用过的模块,负责标记“枯树叶”minimize: true, // 代码压缩,负责摇落“枯树叶”concatenateModules: true // 尽可能将所有模块合并到一个函数中进行输出,有利于减小代码体积,scope hoisting}}
Tree-Shaking & Babel
Tree-Shaking实现的前提必须使用ES Module来组织我们的代码。新版本的babel会自动根据当前环境将编译过后的代码保持原有的模块组织方式,老版本的babel则没有这个功能,需要我们自己配置,所以尽量下载新版本的babelmodule.exports = {module: {rules: [{test: /\.js$/,use: {loader: 'babel-loader',options: {presets: [['@babel/preset-env', { module: false }] // 关闭module,module的值会默认为auto]}}}]}}
