生产环境

  • 生产环境下,webpack会自动开启tree-shaking

其他环境

  • 其他环境下模拟tree-shaking
    1. module.exports = {
    2. mode: 'none'
    3. entry: './main.js'
    4. output: {
    5. filename: 'bundle.js'
    6. },
    7. optimization: { // 优化项,tree shaking的具体实现
    8. usedExports: true, // 只打包有引用过的模块,负责标记“枯树叶”
    9. minimize: true, // 代码压缩,负责摇落“枯树叶”
    10. concatenateModules: true // 尽可能将所有模块合并到一个函数中进行输出,有利于减小代码体积,scope hoisting
    11. }
    12. }

    Tree-Shaking & Babel

    Tree-Shaking实现的前提必须使用ES Module来组织我们的代码。新版本的babel会自动根据当前环境将编译过后的代码保持原有的模块组织方式,老版本的babel则没有这个功能,需要我们自己配置,所以尽量下载新版本的babel
    1. module.exports = {
    2. module: {
    3. rules: [
    4. {
    5. test: /\.js$/,
    6. use: {
    7. loader: 'babel-loader',
    8. options: {
    9. presets: [
    10. ['@babel/preset-env', { module: false }] // 关闭module,module的值会默认为auto
    11. ]
    12. }
    13. }
    14. }
    15. ]
    16. }
    17. }