Appearance
Nx 详解
简介
Nx 是一个智能、快速的构建系统,用于全栈、跨平台的单体应用和微服务开发。它提供代码生成、依赖图分析、智能构建和分布式缓存等功能,帮助团队在 monorepo 中高效工作。
安装
全局安装 Nx CLI
bash
npm install -g @nx/cli
在现有项目中安装
bash
npm install --save-dev @nx/workspace
npx nx init
创建新 Nx 工作区
bash
npx create-nx-workspace@latest
项目结构
my-nx-workspace/
├── nx.json
├── package.json
├── tsconfig.base.json
├── workspace.json (旧版本)
├── tools/
│ ├── generators/
│ └── executors/
├── apps/
│ ├── frontend/
│ └── backend/
└── libs/
├── ui/
├── data-access/
└── utils/
核心概念
1. 项目(Projects)
Nx 工作区包含多个项目,分为:
- 应用项目(Applications): 可执行的应用程序
- 库项目(Libraries): 可重用的代码模块
2. 依赖图(Dependency Graph)
Nx 自动分析项目间的依赖关系,生成可视化依赖图。
3. 影子测试(Affected Testing)
仅测试受代码更改影响的项目,提高测试效率。
基本命令
1. 创建应用
bash
nx generate @nx/web:app frontend
nx generate @nx/angular:app frontend
nx generate @nx/react:app frontend
2. 创建库
bash
nx generate @nx/workspace:lib shared-ui
nx generate @nx/angular:lib shared-utils
nx generate @nx/react:lib shared-components
3. 构建项目
bash
nx build frontend
nx build --prod
4. 运行开发服务器
bash
nx serve frontend
nx serve frontend --port=4201
5. 运行测试
bash
nx test frontend
nx test --all
nx affected:test
6. 运行 Lint
bash
nx lint frontend
nx affected:lint
高级功能
1. 影子命令(Affected Commands)
bash
nx affected:build
nx affected:test
nx affected:lint
nx affected --target=custom-target
2. 依赖图可视化
bash
nx dep-graph
nx affected:dep-graph
3. 代码生成器(Generators)
bash
nx generate @nx/angular:component my-component --project=my-lib
4. 自定义执行器(Executors)
为特定任务定义自定义构建逻辑。
配置文件
nx.json
Nx 工作区的主要配置文件:
json
{
"npmScope": "myorg",
"affected": {
"defaultBase": "master"
},
"tasksRunnerOptions": {
"default": {
"runner": "@nx/workspace/tasks-runners/default",
"options": {
"cacheableOperations": ["build", "lint", "test", "e2e"]
}
}
},
"targetDependencies": {
"build": [
{
"target": "build",
"projects": "dependencies"
}
]
}
}
插件生态系统
Nx 有丰富的插件生态系统:
- @nx/angular - Angular 支持
- @nx/react - React 支持
- @nx/web - Web 应用支持
- @nx/node - Node.js 支持
- @nx/nest - NestJS 支持
- @nx/next - Next.js 支持
- @nx/expo - Expo 支持
分布式缓存
Nx 提供分布式缓存功能,避免重复构建:
json
{
"tasksRunnerOptions": {
"default": {
"runner": "@nx/workspace/tasks-runners/default",
"options": {
"cacheableOperations": ["build", "lint", "test"],
"accessToken": "your-token",
"parallel": 1
}
}
}
}
代码生成
Nx 提供强大的代码生成能力:
bash
# 生成应用
nx generate @nx/web:app myapp
# 生成库
nx generate @nx/workspace:lib mylib
# 生成组件(以 Angular 为例)
nx generate @nx/angular:component my-component --project=mylib
最佳实践
1. 项目组织
- 将共享代码放在 libs 目录
- 将应用放在 apps 目录
- 使用清晰的命名约定
2. 依赖管理
- 定义清晰的依赖边界
- 避免循环依赖
- 使用 Nx 的依赖约束
3. CI/CD 集成
- 使用影子命令优化 CI 时间
- 启用分布式缓存
- 并行执行任务
优缺点
优点
- 强大的代码生成能力
- 智能的增量构建
- 优秀的性能表现
- 丰富的插件生态系统
- 优秀的开发体验
缺点
- 学习曲线较陡峭
- 对于小型项目可能过于复杂
- 需要遵循 Nx 的约定
与其他工具对比
Nx vs Lerna
- Nx 提供更完整的开发体验
- 自动依赖分析和影子构建
- Lerna 更专注于版本和发布
Nx vs Yarn Workspaces
- Nx 提供构建、测试、生成等完整功能
- Yarn Workspaces 专注于依赖管理
- Nx 有更高级的优化策略