Next.js 项目生产构建优化

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)
默认配置12045
基础优化 + Webpack8538
全量优化5232

注意事项

  1. 部分优化(如 drop_console)需根据项目需求选择
  2. 缓存可能导致构建结果不一致,必要时清理 .next/cache
  3. 生产环境务必关闭 productionBrowserSourceMaps

按此方案优化后,多数项目构建速度可提升 30%~70%。建议逐步实施并验证效果!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风吹落叶花飘荡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值