nx-monorepo

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Nx Monorepo

Nx Monorepo

Overview

概述

Provides comprehensive guidance for working with Nx monorepos in TypeScript/JavaScript projects. Nx is a smart build system with advanced caching, affected command execution, and powerful generators for React, Next.js, NestJS, and more. This skill covers workspace creation, project generation, task execution, caching strategies, Module Federation, and CI/CD integration.
为TypeScript/JavaScript项目中使用Nx monorepo提供全面指南。Nx是一个智能构建系统,具备高级缓存、affected命令执行功能,以及针对React、Next.js、NestJS等框架的强大生成器。本指南涵盖工作区创建、项目生成、任务执行、缓存策略、Module Federation和CI/CD集成等内容。

When to Use

适用场景

Use this skill when:
  • Creating a new Nx workspace or initializing Nx in an existing project
  • Generating applications, libraries, or components with Nx generators
  • Running affected commands or executing tasks across multiple projects
  • Setting up CI/CD pipelines for Nx projects (GitHub Actions, CircleCI, etc.)
  • Configuring Module Federation with React or Next.js
  • Implementing NestJS backend applications within Nx
  • Managing TypeScript package libraries with buildable and publishable libs
  • Setting up remote caching or Nx Cloud
  • Optimizing monorepo build times and caching strategies
  • Debugging dependency graph issues or circular dependencies
Trigger phrases: "create Nx workspace", "Nx monorepo", "generate Nx app", "Nx affected", "Nx CI/CD", "Module Federation Nx", "Nx Cloud"
在以下场景中使用本指南:
  • 创建新的Nx工作区,或在现有项目中初始化Nx
  • 使用Nx生成器生成应用、库或组件
  • 运行affected命令,或在多个项目中执行任务
  • 为Nx项目搭建CI/CD流水线(GitHub Actions、CircleCI等)
  • 为React或Next.js配置Module Federation
  • 在Nx中实现NestJS后端应用
  • 管理可构建、可发布的TypeScript包库
  • 搭建远程缓存或Nx Cloud
  • 优化monorepo构建时间和缓存策略
  • 调试依赖图问题或循环依赖
触发关键词: "create Nx workspace"、"Nx monorepo"、"generate Nx app"、"Nx affected"、"Nx CI/CD"、"Module Federation Nx"、"Nx Cloud"

Instructions

操作指南

Workspace Creation

工作区创建

  1. Create a new workspace with interactive setup:
    bash
    npx create-nx-workspace@latest
    Follow prompts to select preset (Integrated, Standalone, Package-based) and framework stack.
  2. Initialize Nx in an existing project:
    bash
    nx@latest init
  3. Create with specific preset (non-interactive):
    bash
    npx create-nx-workspace@latest my-workspace --preset=react
  1. 通过交互式设置创建新工作区:
    bash
    npx create-nx-workspace@latest
    按照提示选择预设(Integrated、Standalone、Package-based)和技术栈。
  2. 在现有项目中初始化Nx:
    bash
    nx@latest init
  3. 使用指定预设创建(非交互式):
    bash
    npx create-nx-workspace@latest my-workspace --preset=react

Project Generation

项目生成

  1. Generate a React application:
    bash
    nx g @nx/react:app my-app
  2. Generate a library:
    bash
    # React library
    nx g @nx/react:lib my-lib
    
    # TypeScript library
    nx g @nx/js:lib my-util
  3. Generate a component in lib:
    bash
    nx g @nx/react:component my-comp --project=my-lib
  4. Generate NestJS backend:
    bash
    nx g @nx/nest:app my-api
  1. 生成React应用:
    bash
    nx g @nx/react:app my-app
  2. 生成库:
    bash
    # React库
    nx g @nx/react:lib my-lib
    
    # TypeScript库
    nx g @nx/js:lib my-util
  3. 在库中生成组件:
    bash
    nx g @nx/react:component my-comp --project=my-lib
  4. 生成NestJS后端:
    bash
    nx g @nx/nest:app my-api

Task Execution

任务执行

  1. Run tasks for affected projects only:
    bash
    nx affected -t lint test build
  2. Run tasks across all projects:
    bash
    # Build all projects
    nx run-many -t build
    
    # Test specific projects
    nx run-many -t test -p=my-app,my-lib
    
    # Test by pattern
    nx run-many -t test --projects=*-app
  3. Run specific target on single project:
    bash
    nx run my-app:build
  4. Visualize dependency graph:
    bash
    nx graph
  1. 仅为受影响的项目运行任务:
    bash
    nx affected -t lint test build
  2. 在所有项目中运行任务:
    bash
    # 构建所有项目
    nx run-many -t build
    
    # 测试指定项目
    nx run-many -t test -p=my-app,my-lib
    
    # 按模式测试
    nx run-many -t test --projects=*-app
  3. 在单个项目上运行指定目标任务:
    bash
    nx run my-app:build
  4. 可视化依赖图:
    bash
    nx graph

Project Configuration

项目配置

Each project has a
project.json
defining targets, executor, and configurations:
json
{
  "name": "my-app",
  "projectType": "application",
  "sourceRoot": "apps/my-app/src",
  "targets": {
    "build": {
      "executor": "@nx/react:webpack",
      "outputs": ["{workspaceRoot}/dist/apps/my-app"],
      "configurations": {
        "production": {
          "optimization": true
        }
      }
    },
    "test": {
      "executor": "@nx/vite:test"
    }
  },
  "tags": ["type:app", "scope:frontend"]
}
每个项目都有一个
project.json
文件,用于定义目标任务、执行器和配置:
json
{
  "name": "my-app",
  "projectType": "application",
  "sourceRoot": "apps/my-app/src",
  "targets": {
    "build": {
      "executor": "@nx/react:webpack",
      "outputs": ["{workspaceRoot}/dist/apps/my-app"],
      "configurations": {
        "production": {
          "optimization": true
        }
      }
    },
    "test": {
      "executor": "@nx/vite:test"
    }
  },
  "tags": ["type:app", "scope:frontend"]
}

Dependency Management

依赖管理

  1. Set up project dependencies:
    json
    {
      "targets": {
        "build": {
          "dependsOn": [
            { "projects": ["shared-ui"], "target": "build" }
          ]
        }
      }
    }
  2. Use tags for organization:
    json
    { "tags": ["type:ui", "scope:frontend", "platform:web"] }
  1. 设置项目依赖:
    json
    {
      "targets": {
        "build": {
          "dependsOn": [
            { "projects": ["shared-ui"], "target": "build" }
          ]
        }
      }
    }
  2. 使用标签进行组织:
    json
    { "tags": ["type:ui", "scope:frontend", "platform:web"] }

Module Federation (Nx 17+)

Module Federation(Nx 17+)

  1. Generate a remote (micro-frontend):
    bash
    nx g @nx/react:remote checkout --host=dashboard
  2. Generate a host:
    bash
    nx g @nx/react:host dashboard
  1. 生成远程微前端:
    bash
    nx g @nx/react:remote checkout --host=dashboard
  2. 生成宿主应用:
    bash
    nx g @nx/react:host dashboard

CI/CD Setup

CI/CD搭建

Use affected commands in CI to only build/test changed projects:
yaml
undefined
在CI中使用affected命令,仅构建/测试有变更的项目:
yaml
undefined

.github/workflows/ci.yml

.github/workflows/ci.yml

  • run: npx nx affected -t lint --parallel
  • run: npx nx affected -t test --parallel
  • run: npx nx affected -t build --parallel
undefined
  • run: npx nx affected -t lint --parallel
  • run: npx nx affected -t test --parallel
  • run: npx nx affected -t build --parallel
undefined

Examples

示例

Example 1: Create New React Workspace

示例1:创建新React工作区

Input: "Create a new Nx workspace with React and TypeScript"
Steps:
bash
npx create-nx-workspace@latest my-workspace
输入: "Create a new Nx workspace with React and TypeScript"
步骤:
bash
npx create-nx-workspace@latest my-workspace

Select: Integrated Monorepo → React → Integrated monorepo (Nx Cloud)

选择:Integrated Monorepo → React → Integrated monorepo (Nx Cloud)


**Expected Result:** Workspace created with:
- `apps/` directory with React app
- `libs/` directory for shared libraries
- `nx.json` with cache configuration
- CI/CD workflow files ready

**预期结果:** 创建的工作区包含:
- 带有React应用的`apps/`目录
- 用于共享库的`libs/`目录
- 包含缓存配置的`nx.json`
- 就绪的CI/CD工作流文件

Example 2: Run Tests for Changed Projects

示例2:为变更项目运行测试

Input: "Run tests only for projects affected by recent changes"
Command:
bash
nx affected -t test --base=main~1 --head=main
Expected Result: Only tests for projects affected by changes between commits are executed, leveraging cached results from previous runs.
输入: "Run tests only for projects affected by recent changes"
命令:
bash
nx affected -t test --base=main~1 --head=main
预期结果: 仅执行最近提交变更所影响项目的测试,利用之前运行的缓存结果。

Example 3: Generate and Build a Shared Library

示例3:生成并构建共享库

Input: "Create a shared UI library and use it in the app"
Steps:
bash
undefined
输入: "Create a shared UI library and use it in the app"
步骤:
bash
undefined

Generate library

生成库

nx g @nx/react:lib shared-ui
nx g @nx/react:lib shared-ui

Generate component in library

在库中生成组件

nx g @nx/react:component button --project=shared-ui
nx g @nx/react:component button --project=shared-ui

Import in app (tsconfig paths auto-configured)

在应用中导入(tsconfig路径已自动配置)

import { Button } from '@my-workspace/shared-ui'

**Expected Result:** Buildable library at `libs/shared-ui` with proper TypeScript path mapping configured.
import { Button } from '@my-workspace/shared-ui'

**预期结果:** 在`libs/shared-ui`目录下创建可构建的库,并已配置好TypeScript路径映射。

Example 4: Set Up Module Federation

示例4:配置Module Federation

Input: "Configure Module Federation for micro-frontends"
Steps:
bash
undefined
输入: "Configure Module Federation for micro-frontends"
步骤:
bash
undefined

Create host app

创建宿主应用

nx g @nx/react:host dashboard
nx g @nx/react:host dashboard

Add remote to host

为宿主添加远程应用

nx g @nx/react:remote product-catalog --host=dashboard
nx g @nx/react:remote product-catalog --host=dashboard

Start dev servers

启动开发服务器

nx run dashboard:serve nx run product-catalog:serve

**Expected Result:** Two separate applications running where product-catalog loads dynamically into dashboard at runtime.
nx run dashboard:serve nx run product-catalog:serve

**预期结果:** 两个独立应用运行,product-catalog会在运行时动态加载到dashboard中。

Example 5: Debug Build Dependencies

示例5:调试构建依赖

Input: "Why is my app rebuilding when unrelated lib changes?"
Diagnosis:
bash
undefined
输入: "Why is my app rebuilding when unrelated lib changes?"
诊断:
bash
undefined

Show project graph

显示项目依赖图

nx graph --focused=my-app
nx graph --focused=my-app

Check implicit dependencies

检查隐式依赖

nx show project my-app --json | grep implicitDependencies

**Solution:** Add explicit dependency configuration or use `namedInputs` in `nx.json` to exclude certain files from triggering builds.
nx show project my-app --json | grep implicitDependencies

**解决方案:** 添加显式依赖配置,或在`nx.json`中使用`namedInputs`排除某些触发构建的文件。

Best Practices

最佳实践

  • Always use
    nx affected
    in CI
    to only test/build changed projects
  • Organize libs by domain/business capability, not by technical layer
  • Use tags consistently (
    type:app|lib
    ,
    scope:frontend|backend|shared
    )
  • Prevent circular dependencies by configuring
    workspaceLayout
    boundaries in
    nx.json
  • Enable remote caching with Nx Cloud for team productivity
  • Keep project.json simple - use defaults from
    nx.json
    when possible
  • Leverage generators instead of manual file creation for consistency
  • Configure
    namedInputs
    to exclude test files from production cache keys
  • Use Module Federation for independent deployment of micro-frontends
  • Keep workspace generators in
    tools/
    for project-specific scaffolding
  • 在CI中始终使用
    nx affected
    ,仅测试/构建有变更的项目
  • 按领域/业务能力组织库,而非技术层
  • 一致使用标签
    type:app|lib
    scope:frontend|backend|shared
  • 通过在
    nx.json
    中配置
    workspaceLayout
    边界
    避免循环依赖
  • 启用Nx Cloud远程缓存提升团队协作效率
  • 保持project.json简洁 - 尽可能使用
    nx.json
    中的默认配置
  • 使用生成器而非手动创建文件,确保一致性
  • 配置
    namedInputs
    ,将测试文件排除在生产缓存键之外
  • 使用Module Federation实现微前端的独立部署
  • tools/
    中维护工作区生成器
    ,用于项目特定的脚手架搭建

Constraints and Warnings

约束与注意事项

  • Node.js 18.10+ is required for Nx 17+
  • Windows users: Use WSL or Git Bash for best experience
  • First-time setup may take longer due to package installation
  • Large monorepos (50+ projects) should use distributed task execution
  • Module Federation requires webpack 5+ and specific Nx configuration
  • Some generators require additional plugins to be installed first
  • Cache location: Default
    ~/.nx/cache
    can grow large; configure
    cacheDirectory
    in
    nx.json
    if needed
  • Circular dependencies will cause build failures; use
    nx graph
    to visualize
  • Preset migration: Converting between Integrated/Standalone/Package-based requires manual effort
  • Nx 17+需要Node.js 18.10+
  • Windows用户:建议使用WSL或Git Bash以获得最佳体验
  • 首次设置可能因包安装耗时较长
  • **大型monorepo(50+项目)**应使用分布式任务执行
  • Module Federation需要webpack 5+和特定的Nx配置
  • 部分生成器需要先安装额外插件
  • 缓存位置:默认
    ~/.nx/cache
    可能会占用大量空间;如有需要,可在
    nx.json
    中配置
    cacheDirectory
  • 循环依赖会导致构建失败;使用
    nx graph
    可视化依赖关系
  • 预设迁移:在Integrated/Standalone/Package-based之间转换需要手动操作

Reference Files

参考文档

For detailed guidance on specific topics, consult:
TopicReference File
Workspace setup, basic commandsreferences/basics.md
Generators (app, lib, component)references/generators.md
React, Next.js, Expo patternsreferences/react.md
NestJS backend patternsreferences/nestjs.md
TypeScript packagesreferences/typescript.md
CI/CD (GitHub, CircleCI, etc.)references/ci-cd.md
Caching, affected, advancedreferences/advanced.md
如需特定主题的详细指南,请查阅:
主题参考文档
工作区设置、基础命令references/basics.md
生成器(应用、库、组件)references/generators.md
React、Next.js、Expo模式references/react.md
NestJS后端模式references/nestjs.md
TypeScript包references/typescript.md
CI/CD(GitHub、CircleCI等)references/ci-cd.md
缓存、affected命令、高级功能references/advanced.md