
关于
配置和优化 Nx Monorepo 工作区。适用于设置 Nx、配置项目边界、优化构建缓存或实现 affected 命令。
name: nx-workspace-patterns description: "配置和优化 Nx 单体仓库工作区。在设置 Nx、配置项目边界、优化构建缓存或实现 affected 命令时使用。" risk: unknown source: community date_added: "2026-02-27"
Nx 工作区模式
Nx 单体仓库管理的生产模式。
不要在以下情况使用此技能
- 任务与 nx 工作区模式无关
- 你需要此范围之外的不同领域或工具
说明
- 明确目标、约束和所需输入。
- 应用相关最佳实践并验证结果。
- 提供可操作的步骤和验证。
- 如果需要详细示例,打开
resources/implementation-playbook.md。
在以下情况使用此技能
- 设置新的 Nx 工作区
- 配置项目边界
- 使用 affected 命令优化 CI
- 实现远程缓存
- 管理项目间依赖
- 迁移到 Nx
核心概念
1. Nx 架构
workspace/
├── apps/ # 可部署应用
│ ├── web/
│ └── api/
├── libs/ # 共享库
│ ├── shared/
│ │ ├── ui/
│ │ └── utils/
│ └── feature/
│ ├── auth/
│ └── dashboard/
├── tools/ # 自定义执行器/生成器
├── nx.json # Nx 配置
└── workspace.json # 项目配置
2. 库类型
| 类型 | 用途 | 示例 |
|------|---------|---------|
| feature | 智能组件、业务逻辑 | feature-auth |
| ui | 展示组件 | ui-buttons |
| data-access | API 调用、状态管理 | data-access-users |
| util | 纯函数、辅助工具 | util-formatting |
| shell | 应用引导 | shell-web |
模板
模板 1:nx.json 配置
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"npmScope": "myorg",
"affected": {
"defaultBase": "main"
},
"tasksRunnerOptions": {
"default": {
"runner": "nx/tasks-runners/default",
"options": {
"cacheableOperations": [
"build",
"lint",
"test",
"e2e",
"build-storybook"
],
"parallel": 3
}
}
},
"targetDefaults": {
"build": {
"dependsOn": ["^build"],
"inputs": ["production", "^production"],
"cache": true
},
"test": {
"inputs": ["default", "^production", "{workspaceRoot}/jest.preset.js"],
"cache": true
},
"lint": {
"inputs": ["default", "{workspaceRoot}/.eslintrc.json"],
"cache": true
}
}
}
模板 2:项目边界(ESLint 模块边界规则)
{
"rules": {
"@nx/enforce-module-boundaries": [
"error",
{
"depConstraints": [
{ "sourceTag": "type:app", "onlyDependOnLibsWithTags": ["type:feature", "type:ui", "type:util"] },
{ "sourceTag": "type:feature", "onlyDependOnLibsWithTags": ["type:data-access", "type:ui", "type:util"] },
{ "sourceTag": "type:ui", "onlyDependOnLibsWithTags": ["type:util"] },
{ "sourceTag": "type:data-access", "onlyDependOnLibsWithTags": ["type:util"] },
{ "sourceTag": "type:util", "onlyDependOnLibsWithTags": ["type:util"] }
]
}
]
}
}
模板 3:CI 中的 Affected 命令
# 仅构建受影响的项目
npx nx affected --target=build --base=origin/main
# 仅测试受影响的项目
npx nx affected --target=test --base=origin/main
# 仅 lint 受影响的项目
npx nx affected --target=lint --base=origin/main
模板 4:远程缓存(Nx Cloud)
# 连接到 Nx Cloud
npx nx connect-to-nx-cloud
# 或手动配置
# nx.json 中设置 runner 为 "@nrwl/nx-cloud"
最佳实践
- 使用标签和模块边界规则强制依赖方向
- 将 feature 库保持在合理大小——如果太大就拆分
- 使用
affected命令避免不必要的 CI 工作 - 启用远程缓存加速团队构建
- 定期运行
nx graph可视化依赖关系
限制
- 仅在任务明确匹配上述范围时使用此技能。
- 不要将输出视为环境特定验证、测试或专家审查的替代品。
- 如果缺少所需的输入、权限、安全边界或成功标准,请停下来寻求澄清。
兼容工具
Claude CodeCursor
标签
运维部署

