
Monorepo 支持跨包共享代码、统一工具链和原子提交。以下是构建可扩展 Monorepo 的方法。
Turborepo 设置
// package.json
{
"name": "my-monorepo",
"private": true,
"workspaces": ["apps/*", "packages/*"],
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev --parallel",
"test": "turbo run test",
"lint": "turbo run lint"
},
"devDependencies": { "turbo": "^2.0.0" }
}
// turbo.json
{
"$schema": "https://turbo.build/schema.json",
"remoteCache": { "enabled": true },
"tasks": {
"build": {
"dependsOn": ["^build"],
"inputs": ["src/**", "package.json", "tsconfig.json"],
"outputs": ["dist/**", ".next/**"]
},
"test": {
"dependsOn": ["build"],
"cache": true
},
"dev": {
"cache": false,
"persistent": true
}
}
}

包架构
apps/
├── web/ # Next.js
├── mobile/ # React Native
└── api/ # Node.js
packages/
├── ui/ # 共享组件
├── utils/ # 共享工具函数
├── types/ # 共享 TypeScript 类型
└── config/ # 共享 ESLint/TS 配置
// packages/ui/package.json
{
"name": "@company/ui",
"main": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./button": "./src/components/button/index.ts"
},
"scripts": {
"build": "tsup src/index.ts --format esm,cjs --dts"
},
"peerDependencies": { "react": ">=18" }
}

共享 TypeScript 配置
// packages/config/tsconfig-base.json
{
"compilerOptions": {
"target": "ES2022",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"verbatimModuleSyntax": true
}
}
// apps/web/tsconfig.json
{
"extends": "@company/config/tsconfig-base.json",
"compilerOptions": {
"lib": ["ES2022", "DOM"],
"module": "ESNext",
"jsx": "react-jsx"
}
}

使用远程缓存的 CI
# .github/workflows/ci.yml
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- run: npm ci
- run: turbo run build test lint
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
# 远程缓存:未更改的包耗时 0ms
# 典型情况:20 分钟 CI → 缓存命中时 2 分钟
针对超大型仓库的 Nx
# 受影响命令:仅处理更改的包
nx affected --target=build --base=origin/main
nx affected --target=test --base=HEAD~1
# 生成库
nx generate @nx/react:library --name=feature-auth
# 依赖图可视化
nx graph
Monorepo 的投入在第二个应用需要第一个应用的代码时就会得到回报。围绕功能领域而非技术层设计边界。
→ 使用 JSON Viewer 工具分析你的 package.json 依赖。