Webpack 作为现代前端构建工具的核心,其性能优化对开发体验至关重要。以下是针对多进程处理、代码分割和摇树优化的详细解决方案:
module.exports = {
module: {
rules: [
{
test: /\.js$/,
include: path.resolve('src'),
use: [
{
loader: 'thread-loader',
options: {
workers: require('os').cpus().length - 1, // CPU核心数减1
workerParallelJobs: 50,
poolTimeout: 2000
}
},
'babel-loader'
]
}
]
}
}
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimizer: [
new TerserPlugin({
parallel: true, // 启用并行压缩
terserOptions: {
// 其他压缩选项
}
})
]
}
}
const HappyPack = require('happypack');
const happyThreadPool = HappyPack.ThreadPool({ size: 5 });
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: 'happypack/loader?id=js',
include: [path.resolve('src')]
}
]
},
plugins: [
new HappyPack({
id: 'js',
threadPool: happyThreadPool,
loaders: ['babel-loader']
})
]
}
// 使用import()语法实现按需加载
button.addEventListener('click', () => {
import('./module').then(module => {
module.default();
});
});
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
}
}
}
}
}
// React示例
const Home = React.lazy(() => import('./routes/Home'));
const About = React.lazy(() => import('./routes/About'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Router>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Router>
</Suspense>
);
}
module.exports = {
mode: 'production', // 必须为production
optimization: {
usedExports: true,
sideEffects: true
}
}
{
"sideEffects": [
"*.css",
"*.scss",
"@babel/polyfill"
]
}
{
"presets": [
["@babel/preset-env", { "modules": false }] // 必须设置modules: false
]
}
const PurgeCSSPlugin = require('purgecss-webpack-plugin');
const glob = require('glob');
module.exports = {
plugins: [
new PurgeCSSPlugin({
paths: glob.sync(`${path.join(__dirname, 'src')}/**/*`, { nodir: true })
})
]
}
缓存优化:
cache-loader
babel-loader
的 cacheDirectory
DLL 预编译:
const DllPlugin = require('webpack/lib/DllPlugin');
module.exports = {
entry: {
vendor: ['react', 'react-dom', 'lodash']
},
output: {
filename: '[name].dll.js',
path: path.resolve(__dirname, 'dist'),
library: '[name]_[hash]'
},
plugins: [
new DllPlugin({
name: '[name]_[hash]',
path: path.join(__dirname, 'dist', '[name]-manifest.json')
})
]
};
资源压缩:
image-webpack-loader
compression-webpack-plugin
生成gzip文件分析工具:
webpack-bundle-analyzer
分析包内容speed-measure-webpack-plugin
测量各loader/plugin耗时通过以上多方面的优化组合,可以显著提升Webpack的构建速度和应用性能。建议根据项目实际情况选择适合的优化策略,并定期使用分析工具检查优化效果。