正在加载,请稍候…

Monorepo 策略:Turborepo、Nx、远程缓存与包架构

使用 Turborepo 和 Nx 设计可扩展的 Monorepo。涵盖远程缓存、任务编排、共享包架构、代码生成以及大型 JavaScript 代码库的 CI

Monorepo 策略:Turborepo、Nx、远程缓存与包架构

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
    }
  }
}

Monorepo 策略:Turborepo、Nx、远程缓存与包架构 插图

包架构

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" }
}

Monorepo 策略:Turborepo、Nx、远程缓存与包架构 插图

共享 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"
  }
}

Monorepo 策略:Turborepo、Nx、远程缓存与包架构 插图

使用远程缓存的 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 依赖。