Appearance
构建优化
构建优化是提升Web应用性能的关键环节,通过对构建过程的优化可以显著减少包体积、加快构建速度并改善最终用户的体验。
构建工具优化
Webpack优化配置
代码分割
通过代码分割减少初始包体积:
javascript
// webpack.config.js
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
priority: 10,
chunks: 'all'
},
common: {
name: 'common',
minChunks: 2,
chunks: 'all',
enforce: true
}
}
}
}
};
Tree Shaking
启用Tree Shaking移除未使用的代码:
javascript
// webpack.config.js
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
sideEffects: false
}
};
// package.json
{
"sideEffects": [
"./src/polyfills.js"
]
}
Rollup优化
适合构建库的优化配置:
javascript
// rollup.config.js
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'esm',
sourcemap: true
},
plugins: [
resolve(),
commonjs(),
terser() // 压缩代码
]
};
压缩优化
JavaScript压缩
使用Terser进行高级压缩:
javascript
// webpack配置
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true, // 移除console
drop_debugger: true, // 移除debugger
pure_funcs: ['console.log'] // 移除指定函数
}
}
})
]
}
};
CSS压缩
javascript
// webpack配置
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
module.exports = {
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css'
})
],
optimization: {
minimizer: [
new CssMinimizerPlugin()
]
}
};
资源优化
图片资源优化
javascript
// webpack配置图片优化
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'image-webpack-loader',
options: {
mozjpeg: { progressive: true, quality: 65 },
optipng: { enabled: false },
pngquant: { quality: [0.65, 0.90], speed: 4 },
gifsicle: { interlaced: false }
}
}
]
}
]
}
};
字体优化
javascript
// 预加载关键字体
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
// 预加载关键资源
preload: ['*.woff2', '*.woff']
})
]
};
缓存策略
长期缓存配置
javascript
// webpack配置长期缓存
module.exports = {
output: {
filename: '[name].[contenthash].js',
chunkFilename: '[name].[contenthash].chunk.js'
},
optimization: {
moduleIds: 'deterministic',
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
}
}
}
}
};
构建分析
包分析工具
javascript
// webpack-bundle-analyzer配置
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
reportFilename: 'bundle-report.html'
})
]
};
构建时间分析
javascript
// speed-measure-webpack-plugin配置
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();
module.exports = smp.wrap({
// 你的webpack配置
});
现代化构建
使用现代JavaScript语法
javascript
// 针对现代浏览器的优化
module.exports = {
optimization: {
splitChunks: {
cacheGroups: {
modern: {
test: /modern/,
name: 'modern',
chunks: 'all',
priority: 20
}
}
}
}
};
预构建依赖
javascript
// Vite配置预构建依赖
export default {
optimizeDeps: {
include: ['lodash-es', 'axios'],
exclude: ['my-lib']
}
};
构建缓存
持久化缓存
javascript
// Webpack 5 持久化缓存
module.exports = {
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
}
};
Docker构建缓存
text
# Dockerfile优化构建缓存
FROM node:alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
FROM node:alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/server.js"]
CI/CD优化
并行构建
yaml
# GitHub Actions并行构建
build:
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
node-version: [14.x, 16.x]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run build
最佳实践
构建性能检查清单
- 启用压缩和最小化
- 实现代码分割
- 使用长期缓存
- 优化依赖项
- 移除未使用的代码
- 预加载关键资源
- 启用持久化缓存
- 监控构建大小
- 使用现代构建工具
- 定期分析构建报告
监控构建性能
javascript
// 构建性能监控
const buildStartTime = Date.now();
process.on('exit', () => {
const buildTime = Date.now() - buildStartTime;
console.log(`Build completed in ${buildTime}ms`);
if (buildTime > 60000) { // 超过1分钟警告
console.warn('Build time exceeded threshold');
}
});
通过实施这些构建优化策略,可以显著提升构建效率和最终产品的性能表现。