Next.js 项目生产构建优化的完整教程,涵盖配置、工具链和性能调优技巧,助你显著加速 npm run build
:
注:学习阶段请先测试环境使用!
一、基础优化
1. 确保使用最新版本
npm update next react react-dom --save
2. 清理无用依赖和代码
# 分析包大小
npx depcheck
npx npm-check-unused
3. 配置 next.config.js
基础优化项
// next.config.js
module.exports = {
productionBrowserSourceMaps: false, // 关闭生产环境 SourceMap
compress: true, // 启用 Gzip/Brotli 压缩
images: {
formats: ['image/webp'], // 优先生成 WebP 格式
minimumCacheTTL: 3600, // 图片缓存时间
},
};
二、Webpack 优化
1. 启用多线程压缩(TerserPlugin)
npm install terser-webpack-plugin --save-dev
// next.config.js
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
webpack: (config) => {
config.optimization.minimizer = [
new TerserPlugin({
parallel: true, // 启用多线程
terserOptions: {
compress: { drop_console: true }, // 移除 console
},
}),
];
return config;
},
};
2. 启用持久化缓存
// next.config.js
module.exports = {
webpack: (config, { dev, isServer }) => {
if (!dev && !isServer) {
config.cache = {
type: 'filesystem',
buildDependencies: {
config: [__filename],
},
};
}
return config;
},
};
三、环境与构建参数优化
1. 增加 Node.js 内存限制
# 在 package.json 中修改
"scripts": {
"build": "NODE_OPTIONS='--max-old-space-size=4096' next build"
}
2. 选择性生成静态页面
# 仅构建必要页面(适用于部分静态站点)
next build --profile --debug
四、使用分析工具
1. 构建产物分析
npm install @next/bundle-analyzer --save-dev
// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({});
ANALYZE=true npm run build
2. 构建时间分析
npm install --save-dev speed-measure-webpack-plugin
// next.config.js
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();
module.exports = smp.wrap({
// 原有配置
});
五、硬件级优化
1. 使用 SSD 磁盘
- 机械硬盘 → SSD 可提升 50% 以上构建速度
2. 增加 CPU 核心
- Webpack 并行处理能力与 CPU 核心数正相关
3. 使用 SWC 替代 Babel(Next.js 13+ 默认)
// next.config.js
module.exports = {
experimental: {
forceSwcTransforms: true, // 强制使用 SWC
},
};
六、高级技巧
1. 模块联邦(微前端场景)
// next.config.js
const { ModuleFederationPlugin } = require('webpack').container;
module.exports = {
webpack: (config) => {
config.plugins.push(
new ModuleFederationPlugin({
name: 'host',
remotes: {
app1: 'app1@http://localhost:3001/remoteEntry.js',
},
})
);
return config;
},
};
2. 增量构建(仅限 monorepo)
# 使用 Turborepo 加速 monorepo 构建
npm install turbo --save-dev
// package.json
"scripts": {
"build": "turbo run build"
}
七、优化效果验证
1. 构建时间对比
# 优化前
time npm run build
# 优化后
time npm run build
2. 产物大小检查
ls -lh .next/static/chunks
优化前后对比示例
优化项 | 构建时间 (s) | 产物大小 (MB) |
---|---|---|
默认配置 | 120 | 45 |
基础优化 + Webpack | 85 | 38 |
全量优化 | 52 | 32 |
注意事项
- 部分优化(如
drop_console
)需根据项目需求选择 - 缓存可能导致构建结果不一致,必要时清理
.next/cache
- 生产环境务必关闭
productionBrowserSourceMaps
按此方案优化后,多数项目构建速度可提升 30%~70%。建议逐步实施并验证效果!