shared-monorepo-nx

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Monorepo Orchestration with Nx

基于Nx的单体仓库编排

Quick Guide: Nx 22 for monorepo orchestration and build intelligence. Project graph for dependency analysis. Task pipelines with topological ordering and
dependsOn
. Local computation caching + Nx Cloud remote caching for massive speed gains. Inferred tasks (Project Crystal) auto-detect targets from tool config files.
nx affected
runs only what changed.
nx release
for versioning, changelogs, and publishing. Generators scaffold code, executors run tasks.

<critical_requirements>
快速指南: Nx 22 用于单体仓库编排与构建智能。项目图谱用于依赖分析。支持拓扑排序与
dependsOn
的任务流水线。本地计算缓存 + Nx Cloud 远程缓存实现大幅提速。自动推断任务(Project Crystal)可从工具配置文件中自动检测目标。
nx affected
仅运行变更相关任务。
nx release
用于版本管理、变更日志生成与发布。生成器用于代码脚手架,执行器用于运行任务。

<critical_requirements>

CRITICAL: Before Using This Skill

重要提示:使用此技能前须知

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type
, named constants)
(You MUST enable caching with
"cache": true
on cacheable targets — builds, tests, linting — and set
"cache": false
or omit for side-effect tasks like
serve
)
(You MUST define
dependsOn: ["^build"]
in targetDefaults for build tasks to ensure topological ordering across the project graph)
(You MUST declare
inputs
and
outputs
for cached targets so Nx knows what to hash and what to restore)
(You MUST use inferred tasks (Project Crystal) as the default — only add
project.json
targets when overriding inferred configuration)
(You MUST use
nx affected -t <target>
in CI to only run tasks for changed projects and their dependents)
</critical_requirements>

Auto-detection: Nx workspace, nx.json, project.json, nx generate, nx affected, nx graph, nx release, @nx/ plugins, Nx Cloud, inferred tasks, Project Crystal, nx migrate, targetDefaults, namedInputs, nx run-many, nx serve
When to use:
  • Setting up a new Nx monorepo or adding Nx to an existing repo
  • Configuring task pipelines, caching, and dependency ordering in nx.json
  • Generating projects, libraries, and components with Nx generators
  • Running affected commands to optimize CI builds
  • Configuring Nx Cloud for remote caching and distributed task execution
  • Managing releases with
    nx release
    (versioning, changelogs, publishing)
  • Setting up module federation for micro-frontend architectures
  • Migrating between Nx versions with
    nx migrate
When NOT to use:
  • Single application with no shared libraries (standard build tools suffice)
  • Projects already using Turborepo (do not mix monorepo orchestrators)
  • Very small projects where Nx setup overhead exceeds benefits
  • When all you need is
    npm workspaces
    without task orchestration
Key patterns covered:
  • Workspace setup and nx.json configuration
  • Task pipelines with
    targetDefaults
    and
    dependsOn
  • Local + remote caching strategies
  • Inferred tasks (Project Crystal) and plugin system
  • Affected commands and project graph
  • Generators and executors
  • Release management (
    nx release
    )
  • Module federation for micro-frontends
所有代码必须遵循CLAUDE.md中的项目约定(短横线命名、命名导出、导入排序、
import type
、命名常量)
(必须为可缓存目标——构建、测试、代码检查——启用
"cache": true
,对于
serve
等有副作用的任务,设置
"cache": false
或省略该配置)
(必须在build任务的targetDefaults中定义
dependsOn: ["^build"]
,以确保跨项目图谱的拓扑排序)
(必须为可缓存目标声明
inputs
outputs
,以便Nx知道需要哈希哪些内容以及恢复哪些内容)
(必须默认使用自动推断任务(Project Crystal)——仅在需要覆盖推断配置时添加
project.json
目标)
(必须在CI中使用
nx affected -t <target>
,仅为变更项目及其依赖项运行任务)
</critical_requirements>

自动检测项: Nx工作区、nx.json、project.json、nx generate、nx affected、nx graph、nx release、@nx/插件、Nx Cloud、自动推断任务、Project Crystal、nx migrate、targetDefaults、namedInputs、nx run-many、nx serve
适用场景:
  • 搭建新的Nx单体仓库或为现有仓库添加Nx
  • 在nx.json中配置任务流水线、缓存及依赖排序
  • 使用Nx生成器创建项目、库及组件
  • 运行affected命令优化CI构建
  • 配置Nx Cloud实现远程缓存与分布式任务执行
  • 使用
    nx release
    管理版本(版本控制、变更日志、发布)
  • 为微前端架构设置模块联邦
  • 通过
    nx migrate
    在不同Nx版本间迁移
不适用场景:
  • 无共享库的单一应用(标准构建工具已足够)
  • 已使用Turborepo的项目(不要混合使用单体仓库编排工具)
  • Nx设置成本超过收益的极小项目
  • 仅需
    npm workspaces
    而无需任务编排的场景
涵盖的核心模式:
  • 工作区搭建与nx.json配置
  • 基于
    targetDefaults
    dependsOn
    的任务流水线
  • 本地+远程缓存策略
  • 自动推断任务(Project Crystal)与插件系统
  • Affected命令与项目图谱
  • 生成器与执行器
  • 版本发布管理(
    nx release
  • 微前端的模块联邦

Examples

示例

  • Workspace Setup — Directory structure, nx.json config
  • Task Pipeline & Caching — dependsOn ordering, namedInputs, cache configuration, affected commands
  • Generators — Built-in generators, custom generators, schemas, migrations
  • CI & Release Management — GitHub Actions, Nx Cloud, release configuration, module federation
Additional resources:
  • For CLI reference and decision frameworks, see reference.md

<philosophy>
  • 工作区搭建 — 目录结构、nx.json配置
  • 任务流水线与缓存 — dependsOn排序、namedInputs、缓存配置、affected命令
  • 生成器 — 内置生成器、自定义生成器、模式、迁移
  • CI与版本发布管理 — GitHub Actions、Nx Cloud、发布配置、模块联邦
额外资源:
  • 如需CLI参考与决策框架,请查看reference.md

<philosophy>

Philosophy

设计理念

Nx is a build intelligence platform for monorepos. Unlike simple task runners, Nx understands the structure of your codebase through the project graph — a directed acyclic graph of projects and their dependencies. This graph enables intelligent task scheduling, fine-grained caching, and affected analysis.
Nx's core value proposition: never run a task that has already been computed, and never run more tasks than necessary.
Key principles:
  • Project graph first — Nx analyzes imports, configuration, and dependency relationships to build a graph of your workspace. Every feature (caching, affected, task pipelines) builds on this graph.
  • Inferred configuration — Since Project Crystal (Nx 18+), plugins auto-detect tasks from tool configs (vite.config.ts, jest.config.ts, etc.), dramatically reducing boilerplate.
  • Computation caching — Every task result is cached by default. Cache keys are computed from file inputs, environment, and dependency graph position.
  • Affected analysis
    nx affected
    uses git diff + project graph to determine the minimum set of projects impacted by a change.
When to use Nx:
  • Monorepos with multiple apps sharing libraries
  • Teams needing remote cache sharing across developers and CI
  • Large codebases where build/test times are a bottleneck
  • Projects with complex task dependency chains requiring topological ordering
  • Organizations wanting enforced module boundaries between teams
When NOT to use Nx:
  • Single-app projects with no shared code (Vite/esbuild directly)
  • Polyrepo setups where repos are intentionally independent
  • Projects already using Turborepo (pick one orchestrator)
  • Prototypes or very small projects where setup cost exceeds benefit
</philosophy>
<patterns>
Nx是面向单体仓库的构建智能平台。与简单的任务运行器不同,Nx通过项目图谱——项目及其依赖项的有向无环图——理解代码库的结构。该图谱支持智能任务调度、细粒度缓存与变更影响分析。
Nx的核心价值主张:绝不重复运行已计算过的任务,绝不运行超出必要范围的任务。
核心原则:
  • 项目图谱优先——Nx分析导入、配置与依赖关系,构建工作区图谱。所有功能(缓存、affected、任务流水线)均基于此图谱构建。
  • 推断式配置——自Project Crystal(Nx 18+)起,插件可从工具配置文件(vite.config.ts、jest.config.ts等)中自动检测任务,大幅减少样板代码。
  • 计算缓存——默认缓存所有任务结果。缓存键由文件输入、环境及依赖图谱位置计算得出。
  • 变更影响分析——
    nx affected
    结合git diff与项目图谱,确定变更影响的最小项目集合。
何时使用Nx:
  • 包含多个共享库应用的单体仓库
  • 需要跨开发者与CI共享远程缓存的团队
  • 构建/测试时间成为瓶颈的大型代码库
  • 存在复杂任务依赖链、需要拓扑排序的项目
  • 希望在团队间强制执行模块边界的组织
何时不使用Nx:
  • 无共享代码的单一应用(直接使用Vite/esbuild即可)
  • 各仓库有意保持独立的多仓库架构
  • 已使用Turborepo的项目(选择一种编排工具即可)
  • 原型或极小项目(设置成本超过收益)
</philosophy>
<patterns>

Core Patterns

核心模式

Pattern 1: Workspace Setup and nx.json Configuration

模式1:工作区搭建与nx.json配置

The
nx.json
file is the central configuration for task behavior, caching, plugins, and workspace-wide defaults.
json
{
  "$schema": "./node_modules/nx/schemas/nx-schema.json",
  "namedInputs": {
    "production": [
      "default",
      "!{projectRoot}/**/*.spec.ts",
      "!{projectRoot}/**/*.test.ts"
    ]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production"],
      "outputs": ["{projectRoot}/dist"],
      "cache": true
    }
  },
  "plugins": [
    { "plugin": "@nx/vite/plugin", "options": { "buildTargetName": "build" } }
  ]
}
Why good:
namedInputs
exclude test files from build cache keys,
dependsOn: ["^build"]
enforces topological ordering, plugins auto-detect targets
For complete nx.json examples, see examples/core.md.

nx.json
文件是任务行为、缓存、插件及工作区全局默认配置的中心。
json
{
  "$schema": "./node_modules/nx/schemas/nx-schema.json",
  "namedInputs": {
    "production": [
      "default",
      "!{projectRoot}/**/*.spec.ts",
      "!{projectRoot}/**/*.test.ts"
    ]
  },
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "inputs": ["production", "^production"],
      "outputs": ["{projectRoot}/dist"],
      "cache": true
    }
  },
  "plugins": [
    { "plugin": "@nx/vite/plugin", "options": { "buildTargetName": "build" } }
  ]
}
优势:
namedInputs
将测试文件排除在构建缓存键之外,
dependsOn: ["^build"]
强制执行拓扑排序,插件自动检测目标
如需完整的nx.json示例,请查看examples/core.md

Pattern 2: Task Pipelines and Dependency Ordering

模式2:任务流水线与依赖排序

Task pipelines define execution order using the
dependsOn
property. The
^
prefix means "run this target on dependencies first" (topological ordering).
json
{
  "targetDefaults": {
    "build": { "dependsOn": ["^build"] },
    "test": { "dependsOn": ["build"] },
    "e2e": { "dependsOn": [{ "target": "serve", "params": "ignore" }] },
    "serve": { "continuous": true, "cache": false }
  }
}
  • "^build"
    — Run
    build
    on dependency projects first (topological)
  • "build"
    — Run
    build
    on the same project first
  • { "target": "serve", "params": "ignore" }
    — Object form, prevents parameter forwarding
  • "continuous": true
    — Long-running task (Nx 21+), dependents start immediately
For pipeline examples and ordering walkthrough, see examples/tasks.md.

任务流水线通过
dependsOn
属性定义执行顺序。
^
前缀表示“先在依赖项上运行此目标”(拓扑排序)。
json
{
  "targetDefaults": {
    "build": { "dependsOn": ["^build"] },
    "test": { "dependsOn": ["build"] },
    "e2e": { "dependsOn": [{ "target": "serve", "params": "ignore" }] },
    "serve": { "continuous": true, "cache": false }
  }
}
  • "^build"
    — 先在依赖项目上运行
    build
    (拓扑排序)
  • "build"
    — 先在当前项目上运行
    build
  • { "target": "serve", "params": "ignore" }
    — 对象形式,防止参数传递
  • "continuous": true
    — 长期运行任务(Nx 21+),依赖项可立即启动
如需流水线示例与排序指南,请查看examples/tasks.md

Pattern 3: Computation Caching (Local + Remote)

模式3:计算缓存(本地+远程)

Nx caches task results locally by default. When inputs have not changed, cached outputs are restored instantly. Nx Cloud extends this with remote caching shared across the team.
json
{
  "namedInputs": {
    "production": ["default", "!{projectRoot}/**/*.test.ts"]
  },
  "targetDefaults": {
    "build": {
      "inputs": ["production", "^production"],
      "outputs": ["{projectRoot}/dist"],
      "cache": true
    },
    "test": {
      "inputs": [
        "default",
        "^production",
        { "externalDependencies": ["vitest"] }
      ],
      "cache": true
    },
    "serve": { "cache": false, "continuous": true }
  }
}
Key concepts:
production
excludes test files from build cache keys,
externalDependencies
invalidates cache on test runner upgrades,
cache: false
on serve prevents caching dev servers
For cache strategies and namedInputs scenarios, see examples/tasks.md.

Nx默认在本地缓存任务结果。当输入未变更时,可立即恢复缓存输出。Nx Cloud将此扩展为团队共享的远程缓存。
json
{
  "namedInputs": {
    "production": ["default", "!{projectRoot}/**/*.test.ts"]
  },
  "targetDefaults": {
    "build": {
      "inputs": ["production", "^production"],
      "outputs": ["{projectRoot}/dist"],
      "cache": true
    },
    "test": {
      "inputs": [
        "default",
        "^production",
        { "externalDependencies": ["vitest"] }
      ],
      "cache": true
    },
    "serve": { "cache": false, "continuous": true }
  }
}
核心概念:
production
将测试文件排除在构建缓存键之外,
externalDependencies
在测试运行器升级时使缓存失效,
cache: false
防止缓存开发服务器
如需缓存策略与namedInputs场景示例,请查看examples/tasks.md

Pattern 4: Inferred Tasks (Project Crystal)

模式4:自动推断任务(Project Crystal)

Since Nx 18, plugins automatically infer tasks from tool configuration files. For example,
@nx/vite/plugin
detects
vite.config.ts
and creates
build
,
serve
, and
test
targets without any
project.json
.
json
{
  "plugins": [
    {
      "plugin": "@nx/vite/plugin",
      "options": { "buildTargetName": "build", "testTargetName": "test" }
    },
    {
      "plugin": "@nx/jest/plugin",
      "include": ["packages/**/*"],
      "exclude": ["**/*-e2e/**/*"]
    }
  ]
}
自Nx 18起,插件可从工具配置文件中自动推断任务。例如,
@nx/vite/plugin
检测到
vite.config.ts
后,无需任何
project.json
即可创建
build
serve
test
目标。
json
{
  "plugins": [
    {
      "plugin": "@nx/vite/plugin",
      "options": { "buildTargetName": "build", "testTargetName": "test" }
    },
    {
      "plugin": "@nx/jest/plugin",
      "include": ["packages/**/*"],
      "exclude": ["**/*-e2e/**/*"]
    }
  ]
}

Configuration Precedence

配置优先级

1. Plugin inferred config (lowest priority)
2. targetDefaults in nx.json
3. project.json or package.json targets (highest priority)
When to use: Always prefer inferred tasks as default. Only add
project.json
targets when overriding:
json
{
  "name": "my-app",
  "targets": {
    "build": { "outputs": ["{projectRoot}/custom-dist"] }
  }
}

1. 插件推断配置(最低优先级)
2. nx.json中的targetDefaults
3. project.json或package.json中的目标(最高优先级)
适用场景: 始终优先使用推断任务。仅在需要覆盖配置时添加
project.json
目标:
json
{
  "name": "my-app",
  "targets": {
    "build": { "outputs": ["{projectRoot}/custom-dist"] }
  }
}

Pattern 5: Affected Commands and Project Graph

模式5:Affected命令与项目图谱

nx affected
uses git diff combined with the project graph to determine which projects need to be rebuilt/tested. This is the primary CI optimization.
bash
npx nx affected -t test                              # Test affected projects
npx nx affected -t build test lint                    # Multiple targets
npx nx affected -t test --base=origin/main --head=HEAD  # Explicit base
npx nx affected --graph                               # Visualize impact
Why good: Only runs tasks for changed projects and their dependents
For CI pipeline examples with affected commands, see examples/ci.md.

nx affected
结合git diff与项目图谱,确定哪些项目需要重新构建/测试。这是CI优化的核心手段。
bash
npx nx affected -t test                              # 测试受影响的项目
npx nx affected -t build test lint                    # 多个目标
npx nx affected -t test --base=origin/main --head=HEAD  # 显式指定基准分支
npx nx affected --graph                               # 可视化影响范围
优势: 仅为变更项目及其依赖项运行任务
如需包含affected命令的CI流水线示例,请查看examples/ci.md

Pattern 6: Generators (Code Scaffolding)

模式6:生成器(代码脚手架)

Generators create and modify code from templates. Set defaults in nx.json
"generators"
to enforce organizational standards (bundler, test runner, style format). Use
npx nx g <plugin>:<generator>
to scaffold projects, libraries, and components.
bash
npx nx g @nx/react:library my-lib --directory=libs/shared/my-lib
npx nx g @nx/workspace:move --project=my-lib --destination=packages/shared/my-lib
For built-in generators, custom generator implementation, and generator defaults, see examples/generators.md.

生成器从模板创建和修改代码。在nx.json的
"generators"
中设置默认值,以强制执行组织标准(打包工具、测试运行器、样式格式)。使用
npx nx g <plugin>:<generator>
来搭建项目、库及组件。
bash
npx nx g @nx/react:library my-lib --directory=libs/shared/my-lib
npx nx g @nx/workspace:move --project=my-lib --destination=packages/shared/my-lib
如需内置生成器、自定义生成器实现及生成器默认配置,请查看examples/generators.md

Pattern 7: Release Management (nx release)

模式7:版本发布管理(nx release)

nx release
orchestrates versioning, changelog generation, and publishing. Supports fixed and independent strategies.
json
{
  "release": {
    "projects": ["packages/*"],
    "projectsRelationship": "independent",
    "version": { "conventionalCommits": true, "updateDependents": "always" },
    "changelog": {
      "projectChangelogs": {
        "file": "{projectRoot}/CHANGELOG.md",
        "createRelease": "github"
      }
    },
    "releaseTag": { "pattern": "{projectName}-v{version}" },
    "git": { "commit": true, "tag": true }
  }
}
bash
npx nx release              # Full release
npx nx release --dry-run    # Preview
npx nx release plan minor -m "Add new API endpoints"  # Version plans
For release configuration examples, see examples/ci.md.

nx release
编排版本控制、变更日志生成与发布。支持固定版本与独立版本策略。
json
{
  "release": {
    "projects": ["packages/*"],
    "projectsRelationship": "independent",
    "version": { "conventionalCommits": true, "updateDependents": "always" },
    "changelog": {
      "projectChangelogs": {
        "file": "{projectRoot}/CHANGELOG.md",
        "createRelease": "github"
      }
    },
    "releaseTag": { "pattern": "{projectName}-v{version}" },
    "git": { "commit": true, "tag": true }
  }
}
bash
npx nx release              # 完整发布流程
npx nx release --dry-run    # 预览发布
npx nx release plan minor -m "Add new API endpoints"  # 版本规划
如需发布配置示例,请查看examples/ci.md

Pattern 8: Module Federation (Micro-Frontends)

模式8:模块联邦(微前端)

Nx provides first-class module federation support, enabling independent teams to deploy separately.
bash
npx nx g @nx/react:host shell --directory=apps/shell
npx nx g @nx/react:remote shop --directory=apps/shop --host=shell
npx nx serve shell --devRemotes=shop,cart
When to use: Large teams with independent deployment cadences. When to avoid: Small teams where a single app suffices.
For module federation examples, see examples/ci.md.
</patterns>
<performance>
Nx提供一流的模块联邦支持,使独立团队能够单独部署。
bash
npx nx g @nx/react:host shell --directory=apps/shell
npx nx g @nx/react:remote shop --directory=apps/shop --host=shell
npx nx serve shell --devRemotes=shop,cart
适用场景: 拥有独立部署节奏的大型团队。不适用场景: 单一应用即可满足需求的小型团队。
如需模块联邦示例,请查看examples/ci.md
</patterns>
<performance>

Performance Optimization

性能优化

Cache Hit Metrics (typical monorepo with 20+ projects):
  • First build: ~60s (no cache, full workspace)
  • Cached build: ~1s (local cache hit, 98% faster)
  • Affected build: ~15s (only changed projects, 75% faster)
  • Remote cache hit: ~5s (download + restore from Nx Cloud)
  • Team savings: 10-40 hours/week with Nx Cloud enabled
Optimization Strategies:
  • Use
    namedInputs
    to exclude test/spec files from build cache keys
  • Set
    outputs
    precisely
    to only cache what is needed (exclude framework caches)
  • Enable Nx Cloud for remote caching — one developer's cache hit benefits the team
  • Use
    nx affected
    in CI to skip unchanged projects entirely
  • Configure
    parallel
    in nx.json to control concurrency
  • Use
    maxCacheSize
    to prevent unbounded cache growth
bash
npx nx build my-app --skip-nx-cache  # Skip cache for a specific run
npx nx reset                          # Clear all cached artifacts
</performance>
<decision_framework>
缓存命中率指标(包含20+项目的典型单体仓库):
  • 首次构建:约60秒(无缓存,全工作区)
  • 缓存命中构建:约1秒(本地缓存命中,提速98%)
  • Affected构建:约15秒(仅变更项目,提速75%)
  • 远程缓存命中:约5秒(从Nx Cloud下载并恢复)
  • 团队收益:启用Nx Cloud后每周节省10-40小时
优化策略:
  • 使用
    namedInputs
    将测试/规范文件排除在构建缓存键之外
  • 精确设置
    outputs
    仅缓存所需内容(排除框架缓存)
  • 启用Nx Cloud 实现远程缓存——一位开发者的缓存命中可惠及整个团队
  • 在CI中使用
    nx affected
    完全跳过未变更项目
  • 在nx.json中配置
    parallel
    控制并发数
  • 使用
    maxCacheSize
    防止缓存无限制增长
bash
npx nx build my-app --skip-nx-cache  # 跳过缓存运行单次构建
npx nx reset                          # 清除所有缓存 artifacts
</performance>
<decision_framework>

Decision Framework

决策框架

When to Use Nx

何时使用Nx

Is this a monorepo with shared code?
├─ NO → Standard build tools (Vite, esbuild, tsc)
└─ YES → Do you need task orchestration and caching?
    ├─ NO → npm/pnpm/bun workspaces alone may suffice
    └─ YES → Do you need a project graph and affected analysis?
        ├─ YES → Nx
        └─ NO → Turborepo may be simpler
这是包含共享代码的单体仓库吗?
├─ 否 → 使用标准构建工具(Vite、esbuild、tsc)
└─ 是 → 是否需要任务编排与缓存?
    ├─ 否 → npm/pnpm/bun workspaces 可能已足够
    └─ 是 → 是否需要项目图谱与变更影响分析?
        ├─ 是 → 使用Nx
        └─ 否 → Turborepo 可能更简单

Nx vs Turborepo

Nx vs Turborepo

Which monorepo tool?
├─ Need project graph analysis → Nx
├─ Need generators and code scaffolding → Nx
├─ Need module federation support → Nx
├─ Need distributed task execution (Nx Agents) → Nx
├─ Need simplest possible config → Turborepo
├─ Already using Vercel ecosystem → Turborepo
└─ Need polyglot support (.NET, Java, Gradle) → Nx
选择哪种单体仓库工具?
├─ 需要项目图谱分析 → Nx
├─ 需要生成器与代码脚手架 → Nx
├─ 需要模块联邦支持 → Nx
├─ 需要分布式任务执行(Nx Agents) → Nx
├─ 需要最简配置 → Turborepo
├─ 已使用Vercel生态系统 → Turborepo
└─ 需要多语言支持(.NET、Java、Gradle) → Nx

Where to Put New Code

新代码存放位置

New code to write?
├─ Deployable application → apps/
├─ Shared across 2+ apps → libs/ or packages/
├─ App-specific code → Feature folder within the app
├─ Build tooling or generators → tools/
└─ Shared configuration → packages/ (e.g., eslint-config, tsconfig)
要编写新代码?
├─ 可部署应用 → apps/
├─ 供2+个应用共享 → libs/ 或 packages/
├─ 应用专属代码 → 应用内的Feature文件夹
├─ 构建工具或生成器 → tools/
└─ 共享配置 → packages/(例如eslint-config、tsconfig)

Fixed vs Independent Releases

固定版本 vs 独立版本

How to version packages?
├─ All packages always release together → "fixed" (default)
├─ Packages have different consumers → "independent"
├─ Internal-only packages → Fixed (simpler)
└─ Published to npm with different audiences → Independent
For comprehensive decision trees and anti-patterns, see reference.md.
</decision_framework>

<integration>
如何为包版本化?
├─ 所有包始终同步发布 → "fixed"(默认)
├─ 包拥有不同的消费者 → "independent"
├─ 仅内部使用的包 → 固定版本(更简单)
└─ 发布到npm且面向不同受众 → 独立版本
如需完整的决策树与反模式,请查看reference.md
</decision_framework>

<integration>

Integration Guide

集成指南

Nx integrates with your tools through its plugin system. Each
@nx/*
plugin detects its tool's config file and infers targets automatically (Project Crystal). You do not need to manually configure targets for supported tools -- install the plugin, add it to
nx.json
plugins
array, and inferred tasks appear.
Plugin model:
@nx/<tool>/plugin
reads the tool's config file (e.g.,
vite.config.ts
,
eslint.config.js
) and registers targets. Use
nx show project <name>
to see what a plugin inferred.
Package managers: Nx works with npm, pnpm, Bun, or Yarn workspaces. No lock-in.
Nx Cloud: Remote caching (Nx Replay) and distributed task execution (Nx Agents). Connect with
nx connect
.
Replaces / Conflicts with:
  • Turborepo: Similar monorepo orchestrator -- choose one, not both
  • Lerna: Nx subsumes Lerna's functionality (Nx team maintains Lerna since v6)
</integration>
<red_flags>
Nx通过其插件系统与现有工具集成。每个
@nx/*
插件检测对应工具的配置文件并自动推断目标(Project Crystal)。对于受支持的工具,无需手动配置目标——安装插件,将其添加到
nx.json
plugins
数组中,即可自动出现推断任务。
插件模型:
@nx/<tool>/plugin
读取工具的配置文件(例如
vite.config.ts
eslint.config.js
)并注册目标。使用
nx show project <name>
查看插件推断的内容。
包管理器: Nx兼容npm、pnpm、Bun或Yarn workspaces,无锁定。
Nx Cloud: 远程缓存(Nx Replay)与分布式任务执行(Nx Agents)。使用
nx connect
连接。
替代/冲突工具:
  • Turborepo: 类似的单体仓库编排工具——选择其一,不要同时使用
  • Lerna: Nx包含Lerna的所有功能(自v6起由Nx团队维护Lerna)
</integration>
<red_flags>

RED FLAGS

警示事项

High Priority Issues:
  • Missing
    dependsOn: ["^build"]
    for build targets — dependencies may not build first, causing import errors
  • Missing
    cache: true
    on cacheable targets — every run recomputes from scratch, negating Nx's primary value
  • Caching long-running tasks (dev servers, watch mode) —
    serve
    and
    dev
    must have
    cache: false
  • Running
    nx run-many -t test
    in CI instead of
    nx affected -t test
    — wastes compute on unchanged projects
  • Missing
    inputs
    on cached targets — Nx cannot determine when cache is stale, leading to incorrect cache hits
Medium Priority Issues:
  • Not using inferred tasks — manually defining every target in
    project.json
    when plugins can auto-detect
  • Missing
    namedInputs
    for production — test file changes invalidate build caches unnecessarily
  • Not connecting to Nx Cloud — every developer rebuilds everything locally instead of sharing cache
  • Overly broad
    outputs
    — caching framework cache directories (
    .next/cache/
    ) bloats cache storage
Common Mistakes:
  • Using
    dependsOn: ["build"]
    (same project) when
    dependsOn: ["^build"]
    (dependency projects) was intended
  • Forgetting to set
    continuous: true
    on serve tasks — dependent e2e tasks wait forever for serve to "complete"
  • Running
    nx migrate
    without
    --run-migrations
    — migrations are generated but not applied
  • Not setting
    defaultBase
    in nx.json — affected analysis defaults to
    main
    which may not be your branch
Gotchas & Edge Cases:
  • dependsOn: ["^task"]
    runs the target on dependency projects;
    dependsOn: ["task"]
    runs it on the same project. Mixing these up causes subtle ordering bugs.
  • nx affected
    requires git history — in CI, ensure
    fetch-depth: 0
    (full history) or at least
    fetch-depth: 2
    for shallow comparison.
  • Plugin order in
    nx.json
    matters — when multiple plugins create the same target name, the last plugin wins.
  • maxCacheSize: "0"
    means unlimited, not zero. To disable caching, use
    cache: false
    on targets.
  • Nx merges
    project.json
    and
    package.json
    scripts. If both define the same target,
    project.json
    takes precedence for configuration but
    package.json
    scripts are still registered as targets.
  • nx reset
    clears the local cache AND shuts down the Nx Daemon. Use
    nx reset --only-cache
    to preserve the daemon.
</red_flags>

<critical_reminders>
高优先级问题:
  • build目标缺少
    dependsOn: ["^build"]
    ——依赖项可能未先构建,导致导入错误
  • 可缓存目标未设置
    cache: true
    ——每次运行都从头计算,完全抵消Nx的核心价值
  • 缓存长期运行任务(开发服务器、监听模式)——
    serve
    dev
    必须设置
    cache: false
  • 在CI中运行
    nx run-many -t test
    而非
    nx affected -t test
    ——在未变更项目上浪费计算资源
  • 可缓存目标缺少
    inputs
    ——Nx无法确定缓存何时过期,导致错误的缓存命中
中优先级问题:
  • 未使用推断任务——当插件可自动检测时,手动在
    project.json
    中定义每个目标
  • 未为生产环境设置
    namedInputs
    ——测试文件变更会不必要地使构建缓存失效
  • 未连接到Nx Cloud——每个开发者都需在本地重新构建所有内容,而非共享缓存
  • outputs
    范围过宽——缓存框架缓存目录(
    .next/cache/
    )会导致缓存存储膨胀
常见错误:
  • 当需要
    dependsOn: ["^build"]
    (依赖项目)时使用了
    dependsOn: ["build"]
    (当前项目)
  • 忘记为serve任务设置
    continuous: true
    ——依赖的e2e任务会无限等待serve“完成”
  • 运行
    nx migrate
    时未添加
    --run-migrations
    ——生成了迁移但未应用
  • 未在nx.json中设置
    defaultBase
    ——变更影响分析默认使用
    main
    分支,可能并非你的分支
陷阱与边缘情况:
  • dependsOn: ["^task"]
    依赖项目上运行目标;
    dependsOn: ["task"]
    当前项目上运行目标。混淆两者会导致微妙的排序错误。
  • nx affected
    需要git历史——在CI中,确保
    fetch-depth: 0
    (完整历史)或至少
    fetch-depth: 2
    用于浅层比较。
  • nx.json中的插件顺序很重要——当多个插件创建相同目标名称时,最后一个插件胜出。
  • maxCacheSize: "0"
    表示无限制,而非零。要禁用缓存,请在目标上使用
    cache: false
  • Nx合并
    project.json
    package.json
    脚本。如果两者定义了相同目标,
    project.json
    的配置优先级更高,但
    package.json
    脚本仍会被注册为目标。
  • nx reset
    清除本地缓存并关闭Nx Daemon。使用
    nx reset --only-cache
    保留Daemon。
</red_flags>

<critical_reminders>

CRITICAL REMINDERS

重要提醒

All code must follow project conventions in CLAUDE.md
(You MUST enable caching with
"cache": true
on cacheable targets — builds, tests, linting — and set
"cache": false
or omit for side-effect tasks like
serve
)
(You MUST define
dependsOn: ["^build"]
in targetDefaults for build tasks to ensure topological ordering across the project graph)
(You MUST declare
inputs
and
outputs
for cached targets so Nx knows what to hash and what to restore)
(You MUST use inferred tasks (Project Crystal) as the default — only add
project.json
targets when overriding inferred configuration)
(You MUST use
nx affected -t <target>
in CI to only run tasks for changed projects and their dependents)
Failure to follow these rules will cause incorrect builds, stale caches, wasted CI compute, and broken task ordering.
</critical_reminders>
所有代码必须遵循CLAUDE.md中的项目约定
(必须为可缓存目标——构建、测试、代码检查——启用
"cache": true
,对于
serve
等有副作用的任务,设置
"cache": false
或省略该配置)
(必须在build任务的targetDefaults中定义
dependsOn: ["^build"]
,以确保跨项目图谱的拓扑排序)
(必须为可缓存目标声明
inputs
outputs
,以便Nx知道需要哈希哪些内容以及恢复哪些内容)
(必须默认使用自动推断任务(Project Crystal)——仅在需要覆盖推断配置时添加
project.json
目标)
(必须在CI中使用
nx affected -t <target>
,仅为变更项目及其依赖项运行任务)
不遵循这些规则将导致构建错误、缓存过期、CI计算资源浪费及任务排序混乱。
</critical_reminders>