nx-monorepo

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Nx Monorepo

Nx Monorepo

Overview

概述

This skill provides expert-level capabilities for Nx monorepo management. Nx is the standard build orchestrator for this AI-native platform.
Why Nx: TypeScript-native, 5-minute setup, auto-generates CLAUDE.md/AGENTS.md for AI assistants, excellent CLI tooling.
本技能提供专业级的Nx monorepo管理能力。Nx是该AI原生平台的标准构建编排工具。
选择Nx的理由: 原生支持TypeScript,5分钟即可完成搭建,可自动为AI助手生成CLAUDE.md/AGENTS.md文件,具备出色的CLI工具链。

Documentation Lookup (On-Demand MCP)

文档查询(按需MCP)

Query Nx documentation via on-demand MCP (no persistent server, 0 startup tokens):
bash
undefined
通过按需MCP查询Nx文档(无需持久化服务器,启动令牌消耗为0):
bash
undefined

Query Nx docs

Query Nx docs

bash scripts/nx-docs.sh "how to configure caching" bash scripts/nx-docs.sh "affected command options"
bash scripts/nx-docs.sh "how to configure caching" bash scripts/nx-docs.sh "affected command options"

List available plugins

List available plugins

bash scripts/nx-plugins.sh

**How it works**: Scripts spawn `nx-mcp` on-demand via stdio, avoiding persistent MCP connections that consume startup tokens.

**Key Insight**: Use **Nx CLI** for operations, scripts for documentation lookup.
bash scripts/nx-plugins.sh

**工作原理**: 脚本通过标准输入输出按需启动`nx-mcp`,避免了消耗启动令牌的持久化MCP连接。

**核心提示**: 使用**Nx CLI**执行操作,使用脚本进行文档查询。

Core CLI Commands

核心CLI命令

Project Graph Analysis

项目图谱分析

bash
undefined
bash
undefined

View interactive project graph

View interactive project graph

nx graph
nx graph

JSON output for programmatic use

JSON output for programmatic use

nx graph --file=output.json
nx graph --file=output.json

Show dependencies of specific project

Show dependencies of specific project

nx graph --focus=my-app
nx graph --focus=my-app

Show what depends on a project

Show what depends on a project

nx graph --affected
undefined
nx graph --affected
undefined

Affected Detection

变更影响检测

bash
undefined
bash
undefined

What's affected since main?

What's affected since main?

nx affected -t build nx affected -t test nx affected -t lint
nx affected -t build nx affected -t test nx affected -t lint

Compare against specific base

Compare against specific base

nx affected -t build --base=origin/main --head=HEAD
nx affected -t build --base=origin/main --head=HEAD

Show affected projects only

Show affected projects only

nx show projects --affected
undefined
nx show projects --affected
undefined

Running Tasks

执行任务

bash
undefined
bash
undefined

Run task for all projects

Run task for all projects

nx run-many -t build nx run-many -t test
nx run-many -t build nx run-many -t test

Run for specific projects

Run for specific projects

nx run-many -t build --projects=app-a,lib-b
nx run-many -t build --projects=app-a,lib-b

Run with parallelism control

Run with parallelism control

nx run-many -t build --parallel=4
nx run-many -t build --parallel=4

Single project

Single project

nx build my-app nx test my-lib
undefined
nx build my-app nx test my-lib
undefined

Code Generation

代码生成

bash
undefined
bash
undefined

List available generators

List available generators

nx list @nx/next nx list @nx/react
nx list @nx/next nx list @nx/react

Generate new application

Generate new application

nx g @nx/next:app my-app nx g @nx/react:app my-frontend
nx g @nx/next:app my-app nx g @nx/react:app my-frontend

Generate library

Generate library

nx g @nx/js:lib shared-utils nx g @nx/react:lib ui-components
nx g @nx/js:lib shared-utils nx g @nx/react:lib ui-components

Dry run (preview)

Dry run (preview)

nx g @nx/next:app my-app --dry-run
undefined
nx g @nx/next:app my-app --dry-run
undefined

Configuration Files

配置文件

nx.json (Workspace Config)

nx.json(工作区配置)

json
{
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "cache": true
    },
    "test": {
      "cache": true
    },
    "lint": {
      "cache": true
    }
  },
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"]
  },
  "defaultBase": "main"
}
json
{
  "targetDefaults": {
    "build": {
      "dependsOn": ["^build"],
      "cache": true
    },
    "test": {
      "cache": true
    },
    "lint": {
      "cache": true
    }
  },
  "namedInputs": {
    "default": ["{projectRoot}/**/*"],
    "production": ["default", "!{projectRoot}/**/*.spec.ts"]
  },
  "defaultBase": "main"
}

project.json (Project Config)

project.json(项目配置)

json
{
  "name": "my-app",
  "projectType": "application",
  "targets": {
    "build": {
      "executor": "@nx/next:build",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/apps/my-app"
      }
    },
    "serve": {
      "executor": "@nx/next:server",
      "options": {
        "buildTarget": "my-app:build"
      }
    }
  }
}
json
{
  "name": "my-app",
  "projectType": "application",
  "targets": {
    "build": {
      "executor": "@nx/next:build",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/apps/my-app"
      }
    },
    "serve": {
      "executor": "@nx/next:server",
      "options": {
        "buildTarget": "my-app:build"
      }
    }
  }
}

Caching

缓存

Local Cache

本地缓存

bash
undefined
bash
undefined

Cache is automatic for cacheable targets

Cache is automatic for cacheable targets

nx build my-app # First run: executes nx build my-app # Second run: cached (instant)
nx build my-app # First run: executes nx build my-app # Second run: cached (instant)

Clear cache

Clear cache

nx reset
undefined
nx reset
undefined

Nx Cloud (Remote Cache)

Nx Cloud(远程缓存)

bash
undefined
bash
undefined

Connect to Nx Cloud

Connect to Nx Cloud

npx nx connect
npx nx connect

Or add manually

Or add manually

nx g @nx/workspace:ci-workflow
nx g @nx/workspace:ci-workflow

Verify connection

Verify connection

nx run-many -t build
nx run-many -t build

Look for: "Remote cache hit"

Look for: "Remote cache hit"

undefined
undefined

Cache Inputs

缓存输入

json
// In project.json or nx.json
{
  "targets": {
    "build": {
      "inputs": [
        "default",
        "^production",
        { "externalDependencies": ["next"] }
      ]
    }
  }
}
json
// In project.json or nx.json
{
  "targets": {
    "build": {
      "inputs": [
        "default",
        "^production",
        { "externalDependencies": ["next"] }
      ]
    }
  }
}

Common Patterns

常见模式

Adding a New JS/TS App

添加新的JS/TS应用

bash
undefined
bash
undefined

1. Add plugin (if not already installed)

1. Add plugin (if not already installed)

pnpm nx add @nx/next # For Next.js pnpm nx add @nx/react # For React pnpm nx add @nx/node # For Node/Express
pnpm nx add @nx/next # For Next.js pnpm nx add @nx/react # For React pnpm nx add @nx/node # For Node/Express

2. Generate app

2. Generate app

pnpm nx g @nx/next:app dashboard --directory=apps/dashboard
pnpm nx g @nx/next:app dashboard --directory=apps/dashboard

3. Verify in graph

3. Verify in graph

pnpm nx graph --focus=dashboard
pnpm nx graph --focus=dashboard

4. Build & Serve

4. Build & Serve

pnpm nx build dashboard pnpm nx serve dashboard
undefined
pnpm nx build dashboard pnpm nx serve dashboard
undefined

Adding a Python App (uv Workspace)

添加Python应用(uv工作区)

Python projects use uv workspaces (similar to pnpm workspaces for JS) with manual
project.json
for Nx:
bash
undefined
Python项目使用uv workspaces(类似JS的pnpm工作区),并为Nx手动配置
project.json
bash
undefined

1. Create directory and initialize

1. Create directory and initialize

mkdir -p apps/my-python-app cd apps/my-python-app uv init uv add --group dev pytest ruff mypy cd ../..
mkdir -p apps/my-python-app cd apps/my-python-app uv init uv add --group dev pytest ruff mypy cd ../..

2. Add to uv workspace (root pyproject.toml)

2. Add to uv workspace (root pyproject.toml)


Edit root `pyproject.toml`:
```toml
[tool.uv.workspace]
members = [
    "apps/panaversity-fs-py",
    "apps/my-python-app",  # Add new project here
]
bash
undefined

编辑根目录下的`pyproject.toml`:
```toml
[tool.uv.workspace]
members = [
    "apps/panaversity-fs-py",
    "apps/my-python-app",  # Add new project here
]
bash
undefined

3. Sync all Python deps from root

3. Sync all Python deps from root

uv sync --extra dev

**apps/my-python-app/project.json** (for Nx):
```json
{
  "name": "my-python-app",
  "projectType": "application",
  "targets": {
    "build": {
      "command": "uv build",
      "options": { "cwd": "apps/my-python-app" }
    },
    "test": {
      "command": "uv run --extra dev pytest",
      "options": { "cwd": "apps/my-python-app" }
    },
    "lint": {
      "command": "uv run --extra dev ruff check .",
      "options": { "cwd": "apps/my-python-app" }
    }
  }
}
bash
undefined
uv sync --extra dev

**apps/my-python-app/project.json**(供Nx使用):
```json
{
  "name": "my-python-app",
  "projectType": "application",
  "targets": {
    "build": {
      "command": "uv build",
      "options": { "cwd": "apps/my-python-app" }
    },
    "test": {
      "command": "uv run --extra dev pytest",
      "options": { "cwd": "apps/my-python-app" }
    },
    "lint": {
      "command": "uv run --extra dev ruff check .",
      "options": { "cwd": "apps/my-python-app" }
    }
  }
}
bash
undefined

4. Verify Nx recognizes it

4. Verify Nx recognizes it

pnpm nx show projects pnpm nx graph --focus=my-python-app
pnpm nx show projects pnpm nx graph --focus=my-python-app

5. Run tasks via Nx

5. Run tasks via Nx

pnpm nx test my-python-app
undefined
pnpm nx test my-python-app
undefined

Shared Python Libraries

共享Python库

Create libraries that multiple Python apps can import:
bash
mkdir -p libs/auth-common-py
cd libs/auth-common-py
uv init --lib
cd ../..
创建可供多个Python应用导入的库:
bash
mkdir -p libs/auth-common-py
cd libs/auth-common-py
uv init --lib
cd ../..

Add to workspace members, then uv sync

Add to workspace members, then uv sync


Reference in dependent projects:
```toml

在依赖项目中引用:
```toml

apps/my-python-app/pyproject.toml

apps/my-python-app/pyproject.toml

[project] dependencies = ["auth-common-py"]
[tool.uv.sources] auth-common-py = { workspace = true }

**Key Insight**: uv manages Python deps via workspace, Nx orchestrates tasks. Single `uv.lock` at root.
[project] dependencies = ["auth-common-py"]
[tool.uv.sources] auth-common-py = { workspace = true }

**核心提示**: uv通过工作区管理Python依赖,Nx负责编排任务。根目录下仅需一个`uv.lock`文件。

Creating Shared Libraries

创建共享库

bash
undefined
bash
undefined

JS/TS UI library

JS/TS UI library

pnpm nx g @nx/react:lib ui --directory=libs/shared/ui
pnpm nx g @nx/react:lib ui --directory=libs/shared/ui

JS/TS Utility library

JS/TS Utility library

pnpm nx g @nx/js:lib utils --directory=libs/shared/utils
pnpm nx g @nx/js:lib utils --directory=libs/shared/utils

Domain library

Domain library

pnpm nx g @nx/js:lib auth --directory=libs/domain/auth
undefined
pnpm nx g @nx/js:lib auth --directory=libs/domain/auth
undefined

CI Pipeline (GitHub Actions)

CI流水线(GitHub Actions)

yaml
name: CI
on: [push, pull_request]

jobs:
  main:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: pnpm/action-setup@v2
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - run: pnpm install --frozen-lockfile

      # Affected-only builds
      - run: npx nx affected -t lint build test --base=origin/main
yaml
name: CI
on: [push, pull_request]

jobs:
  main:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: pnpm/action-setup@v2
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'pnpm'

      - run: pnpm install --frozen-lockfile

      # Affected-only builds
      - run: npx nx affected -t lint build test --base=origin/main

Troubleshooting

故障排除

"Cannot find project"

"Cannot find project"

bash
undefined
bash
undefined

Regenerate project graph

Regenerate project graph

nx reset nx graph
undefined
nx reset nx graph
undefined

Cache Not Working

缓存不生效

bash
undefined
bash
undefined

Verify target is cacheable

Verify target is cacheable

cat nx.json | grep -A5 "targetDefaults"
cat nx.json | grep -A5 "targetDefaults"

Check inputs are stable

Check inputs are stable

nx build my-app --verbose
undefined
nx build my-app --verbose
undefined

Dependency Issues

依赖问题

bash
undefined
bash
undefined

Show project dependencies

Show project dependencies

nx graph --focus=my-app
nx graph --focus=my-app

Check for circular deps

Check for circular deps

nx graph --file=graph.json
nx graph --file=graph.json

Review edges in JSON

Review edges in JSON

undefined
undefined

Quick Reference

快速参考

TaskCommand
Interactive graph
pnpm nx graph
Affected build
pnpm nx affected -t build
Run all tests
pnpm nx run-many -t test
Generate JS/TS app
pnpm nx g @nx/next:app name
Generate JS/TS lib
pnpm nx g @nx/js:lib name
Add plugin
pnpm nx add @nx/next
Clear cache
pnpm nx reset
Show projects
pnpm nx show projects
List generators
pnpm nx list @nx/next
任务命令
交互式图谱
pnpm nx graph
变更影响构建
pnpm nx affected -t build
运行所有测试
pnpm nx run-many -t test
生成JS/TS应用
pnpm nx g @nx/next:app name
生成JS/TS库
pnpm nx g @nx/js:lib name
添加插件
pnpm nx add @nx/next
清除缓存
pnpm nx reset
显示项目列表
pnpm nx show projects
列出生成器
pnpm nx list @nx/next

Python-Specific (uv)

Python专属(uv)

TaskCommand
Init Python project
cd apps/name && uv init
Add runtime dep
uv add <package>
Add dev dep
uv add --group dev <package>
Sync deps
uv sync --extra dev
Run via Nx
pnpm nx test my-python-app
任务命令
初始化Python项目
cd apps/name && uv init
添加运行时依赖
uv add <package>
添加开发依赖
uv add --group dev <package>
同步依赖
uv sync --extra dev
通过Nx运行
pnpm nx test my-python-app

Related Skills

相关技能

  • monorepo-workflow: PR stacking, trunk-based development, code review
  • monorepo-team-lead: CODEOWNERS, human-AI task routing, RFC process
  • monorepo-workflow: PR堆叠、基于主干的开发、代码审查
  • monorepo-team-lead: CODEOWNERS、人机AI任务路由、RFC流程