• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    Webpack打包速度优化方案汇总

    发布者: 天下网吧 | 发布时间: 2025-6-16 07:37| 查看数: 77| 评论数: 0|帖子模式

    一、基础配置优化


    1.1 区分开发与生产环境
    1. // webpack.config.js
    2. module.exports = (env, argv) => {
    3.   const isProduction = argv.mode === 'production';
    4.   
    5.   return {
    6.     mode: isProduction ? 'production' : 'development',
    7.     devtool: isProduction ? 'source-map' : 'eval-cheap-module-source-map',
    8.     // 其他配置...
    9.   };
    10. };
    复制代码
    优化点

    • 开发环境使用更快的 sourcemap 生成方式
    • 生产环境启用完整优化但保留 sourcemap

    1.2 减少解析范围
    1. module.exports = {
    2.   module: {
    3.     rules: [
    4.       {
    5.         test: /\.js$/,
    6.         exclude: /node_modules/,
    7.         include: path.resolve(__dirname, 'src'),
    8.         use: ['babel-loader']
    9.       }
    10.     ]
    11.   },
    12.   resolve: {
    13.     modules: [path.resolve(__dirname, 'src'), 'node_modules'],
    14.     extensions: ['.js', '.jsx'] // 减少扩展名尝试
    15.   }
    16. };
    复制代码
    二、Loader 优化策略


    2.1 限制 loader 应用范围
    1. {
    2.   test: /\.js$/,
    3.   exclude: /node_modules/,
    4.   include: path.resolve(__dirname, 'src'),
    5.   use: ['babel-loader?cacheDirectory']
    6. }
    复制代码
    2.2 启用 loader 缓存
    1. use: [
    2.   {
    3.     loader: 'babel-loader',
    4.     options: {
    5.       cacheDirectory: true // 默认缓存目录 node_modules/.cache/babel-loader
    6.     }
    7.   }
    8. ]
    复制代码
    2.3 减少 loader 数量
    1. // 避免不必要的 loader 调用
    2. {
    3.   test: /\.(jpe?g|png|gif|svg)$/,
    4.   use: [
    5.     {
    6.       loader: 'url-loader',
    7.       options: {
    8.         limit: 8192 // 小于8KB转为base64
    9.       }
    10.     }
    11.     // 移除不必要的 image-webpack-loader 开发环境
    12.   ]
    13. }
    复制代码
    三、插件优化方案


    3.1 选择性使用插件
    1. const plugins = [
    2.   new webpack.DefinePlugin({/*...*/}),
    3.   isProduction && new MiniCssExtractPlugin()
    4. ].filter(Boolean);
    复制代码
    3.2 禁用开发无用插件
    1. plugins: [
    2.   !isDevelopment && new CompressionPlugin(),
    3.   !isDevelopment && new BundleAnalyzerPlugin()
    4. ].filter(Boolean)
    复制代码
    3.3 使用 HardSourceWebpackPlugin
    1. const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

    2. module.exports = {
    3.   plugins: [
    4.     new HardSourceWebpackPlugin()
    5.   ]
    6. };
    复制代码
    效果:二次构建速度提升60%-80%

    四、模块解析优化


    4.1 缩小模块搜索范围
    1. resolve: {
    2.   alias: {
    3.     '@': path.resolve(__dirname, 'src'),
    4.     react: path.resolve(__dirname, './node_modules/react')
    5.   },
    6.   symlinks: false // 防止npm link导致的重复解析
    7. }
    复制代码
    4.2 使用 module.noParse
    1. module: {
    2.   noParse: /jquery|lodash/ // 忽略未模块化的库
    3. }
    复制代码
    五、多进程并行处理


    5.1 thread-loader
    1. module.exports = {
    2.   module: {
    3.     rules: [
    4.       {
    5.         test: /\.js$/,
    6.         use: [
    7.           {
    8.             loader: 'thread-loader',
    9.             options: {
    10.               workers: 2,
    11.               workerParallelJobs: 50,
    12.               poolTimeout: 2000
    13.             }
    14.           },
    15.           'babel-loader'
    16.         ]
    17.       }
    18.     ]
    19.   }
    20. };
    复制代码
    5.2 parallel-webpack
    1. // 安装后直接运行
    2. parallel-webpack --config=webpack.config.js
    复制代码
    5.3 TerserPlugin 多进程
    1. optimization: {
    2.   minimizer: [
    3.     new TerserPlugin({
    4.       parallel: require('os').cpus().length - 1
    5.     })
    6.   ]
    7. }
    复制代码
    六、开发环境特化优化


    6.1 禁用生产环境优化
    1. optimization: {
    2.   removeAvailableModules: false,
    3.   removeEmptyChunks: false,
    4.   splitChunks: false,
    5.   minimize: false
    6. }
    复制代码
    6.2 使用 cache-loader
    1. {
    2.   test: /\.(js|jsx)$/,
    3.   use: [
    4.     'cache-loader',
    5.     'babel-loader'
    6.   ],
    7.   include: path.resolve('src')
    8. }
    复制代码
    6.3 增量编译
    1. watchOptions: {
    2.   aggregateTimeout: 500, // 防抖延迟
    3.   ignored: /node_modules/ // 忽略目录
    4. }
    复制代码
    七、DLL 预编译技术


    7.1 创建 DLL 配置
    1. // webpack.dll.config.js
    2. module.exports = {
    3.   entry: {
    4.     vendor: ['react', 'react-dom', 'lodash']
    5.   },
    6.   output: {
    7.     filename: '[name].dll.js',
    8.     path: path.resolve(__dirname, 'dll'),
    9.     library: '[name]_[hash]'
    10.   },
    11.   plugins: [
    12.     new webpack.DllPlugin({
    13.       name: '[name]_[hash]',
    14.       path: path.join(__dirname, 'dll', '[name]-manifest.json')
    15.     })
    16.   ]
    17. };
    复制代码
    7.2 主配置引用 DLL
    1. // webpack.config.js
    2. plugins: [
    3.   new webpack.DllReferencePlugin({
    4.     manifest: require('./dll/vendor-manifest.json')
    5.   })
    6. ]
    复制代码
    八、高级优化技巧


    8.1 使用 SWC 替代 Babel
    1. module: {
    2.   rules: [
    3.     {
    4.       test: /\.(js|jsx)$/,
    5.       exclude: /node_modules/,
    6.       use: {
    7.         loader: 'swc-loader',
    8.         options: {
    9.           jsc: {
    10.             parser: {
    11.               syntax: 'ecmascript',
    12.               jsx: true
    13.             }
    14.           }
    15.         }
    16.       }
    17.     }
    18.   ]
    19. }
    复制代码
    速度对比:SWC 比 Babel 快 20 倍以上

    8.2 使用 esbuild-loader
    1. const { ESBuildMinifyPlugin } = require('esbuild-loader');

    2. module.exports = {
    3.   module: {
    4.     rules: [
    5.       {
    6.         test: /\.js$/,
    7.         loader: 'esbuild-loader',
    8.         options: {
    9.           target: 'es2015'
    10.         }
    11.       }
    12.     ]
    13.   },
    14.   optimization: {
    15.     minimizer: [
    16.       new ESBuildMinifyPlugin({
    17.         target: 'es2015'
    18.       })
    19.     ]
    20.   }
    21. };
    复制代码
    8.3 模块联邦共享
    1. // 共享依赖避免重复打包
    2. new ModuleFederationPlugin({
    3.   name: 'app1',
    4.   shared: {
    5.     react: { singleton: true },
    6.     'react-dom': { singleton: true }
    7.   }
    8. })
    复制代码
    九、构建分析工具


    9.1 速度分析
    1. const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
    2. const smp = new SpeedMeasurePlugin();

    3. module.exports = smp.wrap({
    4.   // 原webpack配置
    5. });
    复制代码
    9.2 构建耗时分析
    1. class BuildTimePlugin {
    2.   apply(compiler) {
    3.     let startTime;
    4.    
    5.     compiler.hooks.beforeRun.tap('BuildTime', () => {
    6.       startTime = Date.now();
    7.     });
    8.    
    9.     compiler.hooks.done.tap('BuildTime', stats => {
    10.       console.log(`构建耗时: ${(Date.now() - startTime) / 1000}s`);
    11.     });
    12.   }
    13. }
    复制代码
    十、综合优化配置示例
    1. const path = require('path');
    2. const os = require('os');
    3. const webpack = require('webpack');
    4. const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
    5. const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

    6. module.exports = {
    7.   mode: 'development',
    8.   devtool: 'eval-cheap-module-source-map',
    9.   cache: {
    10.     type: 'filesystem',
    11.     buildDependencies: {
    12.       config: [__filename]
    13.     }
    14.   },
    15.   module: {
    16.     rules: [
    17.       {
    18.         test: /\.js$/,
    19.         exclude: /node_modules/,
    20.         use: [
    21.           {
    22.             loader: 'thread-loader',
    23.             options: {
    24.               workers: os.cpus().length - 1
    25.             }
    26.           },
    27.           {
    28.             loader: 'babel-loader',
    29.             options: {
    30.               cacheDirectory: true
    31.             }
    32.           }
    33.         ]
    34.       }
    35.     ]
    36.   },
    37.   plugins: [
    38.     new HardSourceWebpackPlugin(),
    39.     new webpack.ProgressPlugin(),
    40.     process.env.ANALYZE && new BundleAnalyzerPlugin()
    41.   ].filter(Boolean),
    42.   resolve: {
    43.     alias: {
    44.       '@': path.resolve('src')
    45.     },
    46.     extensions: ['.js', '.json']
    47.   },
    48.   optimization: {
    49.     removeAvailableModules: false,
    50.     removeEmptyChunks: false,
    51.     splitChunks: false,
    52.     minimize: false
    53.   },
    54.   stats: {
    55.     modules: false,
    56.     children: false,
    57.     chunks: false,
    58.     chunkModules: false
    59.   }
    60. };
    复制代码
    关键优化指标对比

    优化手段构建时间减少幅度适用场景HardSourceWebpackPlugin60%-80%开发环境thread-loader30%-50%大型项目DLL 预编译40%-60%稳定第三方库SWC/esbuild50%-70%全场景缓存配置70%-90%增量构建
    最佳实践建议


    • 分层优化

      • 开发环境:侧重构建速度(缓存、不压缩)
      • 生产环境:侧重输出质量(Tree Shaking、压缩)

    • 渐进式实施
    1. 1. 添加基础缓存(HardSourceWebpackPlugin)
    2. 2. 引入多进程(thread-loader)
    3. 3. 分析优化重点(SpeedMeasurePlugin)
    4. 4. 实施高级优化(DLL/SWC)
    复制代码
    持续监控

    • 记录每次构建时间
    • 设置性能预算
    1. performance: {
    2.   hints: 'warning',
    3.   maxAssetSize: 500 * 1024,
    4.   maxEntrypointSize: 500 * 1024
    5. }
    复制代码
    通过综合应用这些优化策略,可以将 Webpack 构建速度提升 3-10 倍,显著改善开发体验。建议根据项目实际情况选择性组合使用,并定期使用分析工具评估优化效果。
    以上就是Webpack打包速度优化方案汇总的详细内容,更多关于Webpack打包速度优化的资料请关注脚本之家其它相关文章!

    来源:https://www.jb51.net/javascript/3395375uu.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表