优化项 | 优化前 | 优化后 | 提升 |
---|---|---|---|
构建时间 | 120s | 40s | 66.7% |
首屏加载 | 4.5s | 1.8s | 60% |
打包体积 | 5.2MB | 1.8MB | 65.4% |
// webpack.config.js
module.exports = {
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
}
}
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
optimization: {
minimize: true,
minimizer: [new TerserPlugin({
parallel: true,
terserOptions: {
compress: true,
mangle: true
}
})],
}
}
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
}
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
}
}
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
sideEffects: true
}
}
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
module.exports = {
optimization: {
minimizer: [
new CssMinimizerPlugin({
minimizerOptions: {
preset: [
'default',
{
discardComments: { removeAll: true }
}
]
}
})
]
}
}
// React 示例
const LazyComponent = React.lazy(() => import('./LazyComponent'))
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
)
}
import(/* webpackPreload: true */ 'ChartingLibrary')
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)$/,
use: [
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65
},
pngquant: {
quality: [0.65, 0.90],
speed: 4
}
}
}
]
}
]
}
}
module.exports = {
output: {
filename: '[name].[contenthash].js',
chunkFilename: '[name].[contenthash].js'
}
}
// app1/webpack.config.js
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'app1',
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/Button'
}
})
]
}
// app2/webpack.config.js
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'app2',
remotes: {
app1: 'app1@http://localhost:3001/remoteEntry.js'
}
})
]
}
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: 'report.html',
openAnalyzer: false
})
]
}
# 安装 speed-measure-webpack-plugin
npm install --save-dev speed-measure-webpack-plugin
# 配置使用
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin')
const smp = new SpeedMeasurePlugin()
module.exports = smp.wrap({
// webpack 配置
})
// 使用 web-vitals 监控核心性能指标
import { getCLS, getFID, getLCP } from 'web-vitals'
function sendToAnalytics(metric) {
console.log(metric)
}
getCLS(sendToAnalytics)
getFID(sendToAnalytics)
getLCP(sendToAnalytics)
构建速度:
输出质量:
运行时性能:
通过本文的系统讲解,开发者可以全面掌握 Webpack 性能优化的各项策略与技巧。建议结合实际项目需求,制定合理的优化方案,持续提升应用性能。