Webpack 打包优化实战:从 10s 到 2s 的极致优化

2 阅读1分钟

一、优化前的问题

项目打包时间 10 秒,每次改动都要等很久,开发体验极差。


二、优化策略

1. 代码分割

optimization: {
  splitChunks: {
    chunks: 'all',
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name: 'vendors',
        priority: 10
      }
    }
  }
}

2. 持久化缓存

cache: {
  type: 'filesystem',
  buildDependencies: {
    config: [__filename]
  }
}

3. 多线程编译

use: [
  'thread-loader',
  'babel-loader'
]

4. Tree Shaking

optimization: {
  usedExports: true,
  minimize: true
}

三、优化结果

  • 首次构建:10s → 8s
  • 二次构建:10s → 2s
  • 开发体验大幅提升