Webpack性能优化策略
前端性能优化通过Webpack主要分为构建过程优化和运行效率优化两大方向。以下是具体实施方案:
- 代码拆分与动态加载
1.1 异步模块加载
// React路由异步加载
const Profile = React.lazy(() =>
import(/* webpackChunkName: "profile" */ './components/Profile')
)
// Vue异步组件
const LazyModal = () => ({
component: import('./Modal.vue'),
delay: 300
})
// 交互式加载
button.addEventListener('click', async () => {
const utils = await import('./calculation-utils')
utils.complexCalculation()
})
1.2 分包策略配置
module.exports = {
optimization: {
splitChunks: {
chunks: 'async',
minChunks: 2,
cacheGroups: {
libs: {
test: /[\\/]node_modules[\\/]/,
priority: 15
},
shared: {
minSize: 0,
minChunks: 3,
reuseExistingChunk: true
}
}
}
}
}
- 资源压缩处理
2.1 JS压缩配置
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
optimization: {
minimizer: [
new TerserPlugin({
extractComments: false,
terserOptions: {
compress: {
unused: true,
drop_console: true
}
}
})
]
}
}
2.2 CSS处理优化
const CssMinimizer = require('css-minimizer-webpack-plugin')
const MiniCssPlugin = require('mini-css-extract-plugin')
module.exports = {
module: {
rules: [{
test: /\.scss$/,
use: [MiniCssPlugin.loader, 'css-loader', 'sass-loader']
}]
},
plugins: [new MiniCssPlugin()],
optimization: {
minimizer: [new CssMinimizer()]
}
}
- 长效缓存机制
3.1 哈希文件名
module.exports = {
output: {
filename: '[name].[contenthash].js',
chunkFilename: '[id].[chunkhash].js'
}
}
3.2 模块ID稳定
module.exports = {
optimization: {
moduleIds: 'hashed',
runtimeChunk: 'single'
}
}
- Tree Shaking实施
4.1 生产模式配置
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
sideEffects: true
}
}
4.2 副作用声明
{
"sideEffects": [
"**/*.css",
"src/polyfill.js"
]
}
- 资源预加载
5.1 预加载指令
// 关键资源预加载
import(/* webpackPreload: true */ './core-module')
// 非关键资源预获取
const Settings = () => import(/* webpackPrefetch: true */ './Settings')
- 构建分析工具
6.1 体积分析插件
const Analyzer = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
module.exports = {
plugins: [
new Analyzer({ analyzerMode: 'disabled', generateStatsFile: true })
]
}
- 运行时优化
7.1 外部依赖配置
module.exports = {
externals: {
lodash: '_',
jquery: '$'
}
}
- 高级功能应用
8.1 模块联邦实现
const { ModuleFederationPlugin } = require('webpack').container
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'hostApp',
remotes: {
auth: 'authModule@http://cdn/auth-app.js'
}
})
]
}
- 开发效率提升
9.1 热更新配置
module.exports = {
devServer: {
hot: true,
liveReload: false
}
}
- 性能监控
10.1 资源限制设置
module.exports = {
performance: {
hints: 'error',
maxAssetSize: 250000,
maxEntrypointSize: 400000
}
}
性能评估指标
| 关键指标 | 优化目标 | 检测工具 |
|---|---|---|
| 首屏加载 | < 2.5秒 | Chrome DevTools |
| FCP | < 1.2秒 | Lighthouse |
| 主包体积 | < 150KB | Webpack Stats |
| 缓存复用率 | > 85% | Network面板 |