You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nx monorepo的Next.js项目中实现Bundle Analyzer?

在Nx Monorepo的Next.js项目中集成Bundle Analyzer

步骤1:安装依赖

先安装@next/bundle-analyzer开发依赖:

npm install @next/bundle-analyzer --save-dev
# 或使用yarn
yarn add -D @next/bundle-analyzer

步骤2:修改Next.js配置文件

注意:必须使用next.config.js而非next.config.json,因为需要执行函数式配置。替换原配置内容为:

const { withNx } = require('@nx/next');
// 初始化Bundle Analyzer,仅当环境变量ANALYZE为true时启用
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  // 这里添加你的Next.js基础配置
  reactStrictMode: true,
  swcMinify: true,
  // 其他自定义配置...
};

// 关键:先应用Bundle Analyzer插件,再传入Nx的withNx处理
module.exports = withNx(withBundleAnalyzer(nextConfig));

步骤3:添加分析脚本

在项目根目录的package.json中添加触发分析的脚本(替换your-next-app-name为你的Nx应用名称):

{
  "scripts": {
    "analyze": "ANALYZE=true nx build your-next-app-name"
  }
}

如果需要跨平台兼容(Windows/macOS/Linux),可以先安装cross-env:

npm install cross-env --save-dev

然后修改脚本:

{
  "scripts": {
    "analyze": "cross-env ANALYZE=true nx build your-next-app-name"
  }
}

步骤4:运行分析

执行以下命令启动构建并开启Bundle Analyzer:

npm run analyze
# 或
yarn analyze

构建完成后,浏览器会自动打开分析页面,展示bundle的组成结构。

常见问题排查

  • 若使用next.config.json:该文件无法执行函数式插件配置,必须切换为next.config.js。
  • 版本兼容:确保@nx/next与next、@next/bundle-analyzer的版本匹配,避免依赖冲突。
  • 环境变量未生效:检查终端环境是否正确传递ANALYZE=true,使用cross-env可解决跨平台环境变量问题。

内容的提问来源于stack exchange,提问作者Paul M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:00:10