一、基础配置优化
1.1 区分开发与生产环境
// 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',
// 其他配置...
};
};
优化点:
- 开发环境使用更快的 sourcemap 生成方式
- 生产环境启用完整优化但保留 sourcemap
1.2 减少解析范围
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'] // 减少扩展名尝试
}
};
二、loader 优化策略
2.1 限制 loader 应用范围
{
test: /\.js$/,
exclude: /node_modules/,
include: path.resolve(__dirname, 'src'),
use: ['babel-loader?cachedirectory']
}
2.2 启用 loader 缓存
use: [
{
loader: 'babel-loader',
options: {
cachedirectory: true // 默认缓存目录 node_modules/.cache/babel-loader
}
}
]
2.3 减少 loader 数量
// 避免不必要的 loader 调用
{
test: /\.(jpe?g|png|gif|svg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 8192 // 小于8kb转为base64
}
}
// 移除不必要的 image-webpack-loader 开发环境
]
}
三、插件优化方案
3.1 选择性使用插件
const plugins = [
new webpack.defineplugin({/*...*/}),
isproduction && new minicssextractplugin()
].filter(boolean);
3.2 禁用开发无用插件
plugins: [ !isdevelopment && new compressionplugin(), !isdevelopment && new bundleanalyzerplugin() ].filter(boolean)
3.3 使用 hardsourcewebpackplugin
const hardsourcewebpackplugin = require('hard-source-webpack-plugin');
module.exports = {
plugins: [
new hardsourcewebpackplugin()
]
};
效果:二次构建速度提升60%-80%
四、模块解析优化
4.1 缩小模块搜索范围
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
react: path.resolve(__dirname, './node_modules/react')
},
symlinks: false // 防止npm link导致的重复解析
}
4.2 使用 module.noparse
module: {
noparse: /jquery|lodash/ // 忽略未模块化的库
}
五、多进程并行处理
5.1 thread-loader
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'thread-loader',
options: {
workers: 2,
workerparalleljobs: 50,
pooltimeout: 2000
}
},
'babel-loader'
]
}
]
}
};
5.2 parallel-webpack
// 安装后直接运行 parallel-webpack --config=webpack.config.js
5.3 terserplugin 多进程
optimization: {
minimizer: [
new terserplugin({
parallel: require('os').cpus().length - 1
})
]
}
六、开发环境特化优化
6.1 禁用生产环境优化
optimization: {
removeavailablemodules: false,
removeemptychunks: false,
splitchunks: false,
minimize: false
}
6.2 使用 cache-loader
{
test: /\.(js|jsx)$/,
use: [
'cache-loader',
'babel-loader'
],
include: path.resolve('src')
}
6.3 增量编译
watchoptions: {
aggregatetimeout: 500, // 防抖延迟
ignored: /node_modules/ // 忽略目录
}
七、dll 预编译技术
7.1 创建 dll 配置
// 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')
})
]
};
7.2 主配置引用 dll
// webpack.config.js
plugins: [
new webpack.dllreferenceplugin({
manifest: require('./dll/vendor-manifest.json')
})
]
八、高级优化技巧
8.1 使用 swc 替代 babel
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'swc-loader',
options: {
jsc: {
parser: {
syntax: 'ecmascript',
jsx: true
}
}
}
}
}
]
}
速度对比:swc 比 babel 快 20 倍以上
8.2 使用 esbuild-loader
const { esbuildminifyplugin } = require('esbuild-loader');
module.exports = {
module: {
rules: [
{
test: /\.js$/,
loader: 'esbuild-loader',
options: {
target: 'es2015'
}
}
]
},
optimization: {
minimizer: [
new esbuildminifyplugin({
target: 'es2015'
})
]
}
};
8.3 模块联邦共享
// 共享依赖避免重复打包
new modulefederationplugin({
name: 'app1',
shared: {
react: { singleton: true },
'react-dom': { singleton: true }
}
})
九、构建分析工具
9.1 速度分析
const speedmeasureplugin = require('speed-measure-webpack-plugin');
const smp = new speedmeasureplugin();
module.exports = smp.wrap({
// 原webpack配置
});
9.2 构建耗时分析
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% | 增量构建 |
最佳实践建议
分层优化:
- 开发环境:侧重构建速度(缓存、不压缩)
- 生产环境:侧重输出质量(tree shaking、压缩)
渐进式实施:
1. 添加基础缓存(hardsourcewebpackplugin) 2. 引入多进程(thread-loader) 3. 分析优化重点(speedmeasureplugin) 4. 实施高级优化(dll/swc)
持续监控:
- 记录每次构建时间
- 设置性能预算
performance: {
hints: 'warning',
maxassetsize: 500 * 1024,
maxentrypointsize: 500 * 1024
}
通过综合应用这些优化策略,可以将 webpack 构建速度提升 3-10 倍,显著改善开发体验。建议根据项目实际情况选择性组合使用,并定期使用分析工具评估优化效果。
以上就是webpack打包速度优化方案汇总的详细内容,更多关于webpack打包速度优化的资料请关注代码网其它相关文章!
发表评论