webpack-优化点记录

/post/wp-optimizations article cover image

通用配置

  • 使用最新版本Webpack(V5版本的本地缓存)、Node
  • 通过设置resolve控制资源搜索范围
  • 使用动态加载,减少首屏加载量
  • 正确使用[hash]命中缓存优化http资源请求效率
  • 针对不需要编译的库设置module.noParse跳过编译步骤
  • 使用试验阶段功能experiments.lazyCompilation只构建被使用的入口文件
  • source-map开发环境使用eval(最佳编译速度),生产环境使用source-map(最佳打包质量)
  • 通过设置watchOptions.ignored指明不频繁更新的目录例如node_modules
  • 通过设置module.rules.includemodule.rules.exclude来约束Loader的执行搜索范围(会被打入生产包的除外)
  • 通过设置ts-loader下的transpileOnly: true跳过typescript类型检查使用编辑器插件检查或使用fork-ts-checker-webpack-plugin将类型检测能力剥离到子进程
  • 通过使用eslint-webpack-plugin替代eslint-loader前者在模块构建完毕后执行检查,不会阻断文件加载流程性能更好

开发环境

  • 开发模式禁用产物优化关闭tree-shakingsplitChunksminimizer提升开发环境下的构建性能
js
module.exports = {
  // ...
  mode: "development",
  optimization: {
    removeAvailableModules: false,
    removeEmptyChunks: false,
    splitChunks: false,
    minimize: false,
    concatenateModules: false,
    usedExports: false
  }
}

生产环境

  • optimization.minimizer中分别使用terser-webpack-plugincss-minimizer-webpack-pluginhtml-minifier-terser对对应文件进行压缩减少产出体积

  • 通过webpack-analyzer分析后合理使用SplitChunks分包策略

js
module.exports = {
  // ...
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendor: {
          priority: -10,
          name: "vendors",
          reuseExistingChunk: true,
          test: /[\\/]node_modules[\\/]/
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
          name: 'default',
        },
        react: {
          test: /(react|react-dom)/, // 匹配chunk的名称
          name: 'react', //打包后的文件名
          chunks: 'all',
          priority: 13, // 优先级 越高则先处理
        }
      }
    }
  }
}