9人参与 • 2025-04-24 • Javascript
// webpack.config.js module.exports = (env, argv) => { const isproduction = argv.mode === 'production'; return { mode: isproduction ? 'production' : 'development', devtool: isproduction ? 'source-map' : 'eval-cheap-module-source-map', // 其他配置... }; };
优化点:
module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, include: path.resolve(__dirname, 'src'), use: ['babel-loader'] } ] }, resolve: { modules: [path.resolve(__dirname, 'src'), 'node_modules'], extensions: ['.js', '.jsx'] // 减少扩展名尝试 } };
{ test: /\.js$/, exclude: /node_modules/, include: path.resolve(__dirname, 'src'), use: ['babel-loader?cachedirectory'] }
use: [ { loader: 'babel-loader', options: { cachedirectory: true // 默认缓存目录 node_modules/.cache/babel-loader } } ]
// 避免不必要的 loader 调用 { test: /\.(jpe?g|png|gif|svg)$/, use: [ { loader: 'url-loader', options: { limit: 8192 // 小于8kb转为base64 } } // 移除不必要的 image-webpack-loader 开发环境 ] }
const plugins = [ new webpack.defineplugin({/*...*/}), isproduction && new minicssextractplugin() ].filter(boolean);
plugins: [ !isdevelopment && new compressionplugin(), !isdevelopment && new bundleanalyzerplugin() ].filter(boolean)
const hardsourcewebpackplugin = require('hard-source-webpack-plugin'); module.exports = { plugins: [ new hardsourcewebpackplugin() ] };
效果:二次构建速度提升60%-80%
resolve: { alias: { '@': path.resolve(__dirname, 'src'), react: path.resolve(__dirname, './node_modules/react') }, symlinks: false // 防止npm link导致的重复解析 }
module: { noparse: /jquery|lodash/ // 忽略未模块化的库 }
module.exports = { module: { rules: [ { test: /\.js$/, use: [ { loader: 'thread-loader', options: { workers: 2, workerparalleljobs: 50, pooltimeout: 2000 } }, 'babel-loader' ] } ] } };
// 安装后直接运行 parallel-webpack --config=webpack.config.js
optimization: { minimizer: [ new terserplugin({ parallel: require('os').cpus().length - 1 }) ] }
optimization: { removeavailablemodules: false, removeemptychunks: false, splitchunks: false, minimize: false }
{ test: /\.(js|jsx)$/, use: [ 'cache-loader', 'babel-loader' ], include: path.resolve('src') }
watchoptions: { aggregatetimeout: 500, // 防抖延迟 ignored: /node_modules/ // 忽略目录 }
// webpack.dll.config.js module.exports = { entry: { vendor: ['react', 'react-dom', 'lodash'] }, output: { filename: '[name].dll.js', path: path.resolve(__dirname, 'dll'), library: '[name]_[hash]' }, plugins: [ new webpack.dllplugin({ name: '[name]_[hash]', path: path.join(__dirname, 'dll', '[name]-manifest.json') }) ] };
// webpack.config.js plugins: [ new webpack.dllreferenceplugin({ manifest: require('./dll/vendor-manifest.json') }) ]
module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'swc-loader', options: { jsc: { parser: { syntax: 'ecmascript', jsx: true } } } } } ] }
速度对比:swc 比 babel 快 20 倍以上
const { esbuildminifyplugin } = require('esbuild-loader'); module.exports = { module: { rules: [ { test: /\.js$/, loader: 'esbuild-loader', options: { target: 'es2015' } } ] }, optimization: { minimizer: [ new esbuildminifyplugin({ target: 'es2015' }) ] } };
// 共享依赖避免重复打包 new modulefederationplugin({ name: 'app1', shared: { react: { singleton: true }, 'react-dom': { singleton: true } } })
const speedmeasureplugin = require('speed-measure-webpack-plugin'); const smp = new speedmeasureplugin(); module.exports = smp.wrap({ // 原webpack配置 });
class buildtimeplugin { apply(compiler) { let starttime; compiler.hooks.beforerun.tap('buildtime', () => { starttime = date.now(); }); compiler.hooks.done.tap('buildtime', stats => { console.log(`构建耗时: ${(date.now() - starttime) / 1000}s`); }); } }
const path = require('path'); const os = require('os'); const webpack = require('webpack'); const hardsourcewebpackplugin = require('hard-source-webpack-plugin'); const { bundleanalyzerplugin } = require('webpack-bundle-analyzer'); module.exports = { mode: 'development', devtool: 'eval-cheap-module-source-map', cache: { type: 'filesystem', builddependencies: { config: [__filename] } }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: [ { loader: 'thread-loader', options: { workers: os.cpus().length - 1 } }, { loader: 'babel-loader', options: { cachedirectory: true } } ] } ] }, plugins: [ new hardsourcewebpackplugin(), new webpack.progressplugin(), process.env.analyze && new bundleanalyzerplugin() ].filter(boolean), resolve: { alias: { '@': path.resolve('src') }, extensions: ['.js', '.json'] }, optimization: { removeavailablemodules: false, removeemptychunks: false, splitchunks: false, minimize: false }, stats: { modules: false, children: false, chunks: false, chunkmodules: false } };
优化手段 | 构建时间减少幅度 | 适用场景 |
---|---|---|
hardsourcewebpackplugin | 60%-80% | 开发环境 |
thread-loader | 30%-50% | 大型项目 |
dll 预编译 | 40%-60% | 稳定第三方库 |
swc/esbuild | 50%-70% | 全场景 |
缓存配置 | 70%-90% | 增量构建 |
分层优化:
渐进式实施:
1. 添加基础缓存(hardsourcewebpackplugin) 2. 引入多进程(thread-loader) 3. 分析优化重点(speedmeasureplugin) 4. 实施高级优化(dll/swc)
持续监控:
performance: { hints: 'warning', maxassetsize: 500 * 1024, maxentrypointsize: 500 * 1024 }
通过综合应用这些优化策略,可以将 webpack 构建速度提升 3-10 倍,显著改善开发体验。建议根据项目实际情况选择性组合使用,并定期使用分析工具评估优化效果。
以上就是webpack打包速度优化方案汇总的详细内容,更多关于webpack打包速度优化的资料请关注代码网其它相关文章!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论