module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'thread-loader',
options: {
workers: require('os').cpus().length - 1,
workerParallelJobs: 50,
poolTimeout: 2000
}
},
'babel-loader'
]
}
]
}
}
const HappyPack = require('happypack');
const os = require('os');
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
module.exports = {
plugins: [
new HappyPack({
id: 'js',
threadPool: happyThreadPool,
loaders: ['babel-loader']
})
]
}
// 使用动态import语法
const LazyComponent = () => import(/* webpackChunkName: "lazy-component" */ './LazyComponent');
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
minSize: 30000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
}
module.exports = {
mode: 'production', // 必须为production
optimization: {
usedExports: true,
minimize: true
}
}
// package.json
{
"sideEffects": [
"*.css",
"*.scss",
"@babel/polyfill"
]
}
module.exports = {
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
}
}
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: 'bundle-report.html',
openAnalyzer: false
})
]
}
多进程优化适用场景:
代码分割策略:
摇树优化注意事项:
监控与持续优化:
通过合理组合这些优化技术,通常可以将构建时间减少30%-70%,打包体积缩小20%-50%,具体效果取决于项目结构和配置细节。