TypeScript Monorepo實戰:Turborepo從配置到CI/CD最佳化的6個關鍵策略

前端工程

Monorepo的痛,用過的人才知道

5個套件,3個應用,2套CI設定——每次改個工具函式,你得手動發布npm套件、更新依賴版本、重新部署3個應用。Lerna已經停止維護,Nx學習曲線陡峭,rush設定繁瑣。2026年,Turborepo + pnpm workspace 終於讓TypeScript Monorepo從「能跑」變成「好用」——增量建構、遠端快取、管道編排,一條命令搞定。

本文將從6個關鍵策略出發,帶你完成專案初始化→任務編排→遠端快取→CI/CD最佳化→套件發布→監控告警的全鏈路實戰。


TypeScript Monorepo核心概念

概念 說明
Monorepo 單一程式碼倉庫管理多個套件/應用的工程模式
pnpm workspace pnpm原生Monorepo支援,透過pnpm-workspace.yaml宣告套件目錄
Turborepo Vercel出品的高效能Monorepo建構系統,核心是任務管道和快取
任務管道(Pipeline) 定義任務間的依賴關係和執行順序,如build依賴^build
遠端快取(Remote Cache) 將建構快取上傳到遠端,團隊成員和CI共享快取
增量建構 只重新建構變更的套件及其依賴者,跳過未變更的套件
Changeset 管理套件版本和changelog的工具,支援多套件協同發布
Workspace Protocol pnpm的workspace:*協定,套件間引用始終指向本地原始碼

問題分析:Monorepo的5大挑戰

  1. 依賴地獄:套件A依賴B@1.0,套件C依賴B@2.0,版本衝突難以解決
  2. 建構效能:全量建構耗時從分鐘級到小時級,CI成本飆升
  3. CI/CD設定:每個套件單獨設定流水線,維護成本高且容易不一致
  4. 套件發布流程:多套件版本管理、changelog生成、發布順序協調
  5. 開發體驗:TypeScript專案引用設定複雜,IDE跳轉和型別檢查慢

分步實操:6個關鍵策略

策略1:專案初始化與pnpm workspace

# pnpm-workspace.yaml
packages:
  - "apps/*"
  - "packages/*"
{
  "name": "my-monorepo",
  "private": true,
  "scripts": {
    "build": "turbo run build",
    "dev": "turbo run dev",
    "lint": "turbo run lint",
    "test": "turbo run test",
    "clean": "turbo run clean"
  },
  "devDependencies": {
    "turbo": "^2.3.0",
    "typescript": "^5.7.0"
  },
  "packageManager": "pnpm@9.15.0"
}
// apps/web/package.json
{
  "name": "@my-org/web",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "lint": "eslint . --ext .ts,.tsx",
    "test": "vitest run"
  },
  "dependencies": {
    "@my-org/ui": "workspace:*",
    "@my-org/utils": "workspace:*",
    "next": "^15.0.0",
    "react": "^19.0.0",
    "react-dom": "^19.0.0"
  },
  "devDependencies": {
    "@types/react": "^19.0.0",
    "typescript": "^5.7.0"
  }
}
// packages/ui/package.json
{
  "name": "@my-org/ui",
  "version": "2.1.0",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.mjs",
      "require": "./dist/index.js"
    }
  },
  "scripts": {
    "build": "tsup src/index.ts --format cjs,esm --dts",
    "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
    "lint": "eslint src/",
    "test": "vitest run",
    "clean": "rm -rf dist"
  },
  "peerDependencies": {
    "react": "^19.0.0"
  },
  "devDependencies": {
    "tsup": "^8.0.0",
    "typescript": "^5.7.0",
    "vitest": "^3.0.0"
  }
}

策略2:Turborepo任務管道設定

// turbo.json
{
  "$schema": "https://turbo.build/schema.json",
  "globalDependencies": ["**/.env.*local"],
  "globalEnv": ["NODE_ENV"],
  "tasks": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**", ".next/**", "!.next/cache/**"],
      "outputMode": "new-only"
    },
    "dev": {
      "cache": false,
      "persistent": true,
      "dependsOn": ["^build"]
    },
    "lint": {
      "dependsOn": ["^build"],
      "outputs": []
    },
    "test": {
      "dependsOn": ["build"],
      "outputs": ["coverage/**"],
      "inputs": ["src/**/*.ts", "test/**/*.ts"]
    },
    "clean": {
      "cache": false
    },
    "typecheck": {
      "dependsOn": ["^build"],
      "outputs": []
    }
  }
}
// packages/utils/src/index.ts
export function formatDate(date: Date, locale: string = 'zh-TW'): string {
  return new Intl.DateTimeFormat(locale, {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  }).format(date);
}

export function debounce<T extends (...args: any[]) => any>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timer: ReturnType<typeof setTimeout> | null = null;
  return (...args: Parameters<T>) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

export function deepClone<T>(obj: T): T {
  return structuredClone(obj);
}

export type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };

export function tryCatch<T, E = Error>(fn: () => T): Result<T, E> {
  try {
    return { ok: true, value: fn() };
  } catch (error) {
    return { ok: false, error: error as E };
  }
}

策略3:遠端快取設定

// turbo.json 遠端快取設定
// 方式1:Turborepo Remote Cache(Vercel託管)
// $ npx turbo login
// $ npx turbo link

// 方式2:自託管Remote Cache
# docker-compose.yml - 自託管Turborepo Remote Cache
version: '3.8'
services:
  turbo-cache:
    image: ghcr.io/ducktors/turborepo-remote-cache:latest
    ports:
      - "3001:3000"
    environment:
      - STORAGE_TYPE=s3
      - S3_BUCKET=turbo-cache
      - S3_REGION=us-east-1
      - AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
      - AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
    restart: unless-stopped
# .turbo/config.json 或環境變數設定
# TURBO_API=http://localhost:3001
# TURBO_TOKEN=your-team-token
# TURBO_TEAM=my-team

# CI中使用遠端快取
export TURBO_API="https://cache.my-company.com"
export TURBO_TOKEN="${{ secrets.TURBO_TOKEN }}"
export TURBO_TEAM="my-team"
pnpm turbo run build --remote-cache-only

策略4:CI/CD流水線最佳化

# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

env:
  TURBO_API: ${{ vars.TURBO_API }}
  TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
  TURBO_TEAM: ${{ vars.TURBO_TEAM }}

jobs:
  lint-typecheck:
    name: Lint & TypeCheck
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: pnpm/action-setup@v4
        with:
          version: 9

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: 'pnpm'

      - run: pnpm install --frozen-lockfile

      - run: pnpm turbo run lint typecheck --concurrency=4

  test:
    name: Test
    runs-on: ubuntu-latest
    needs: lint-typecheck
    steps:
      - uses: actions/checkout@v4

      - uses: pnpm/action-setup@v4
        with:
          version: 9

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: 'pnpm'

      - run: pnpm install --frozen-lockfile

      - run: pnpm turbo run test --concurrency=2

      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: coverage-reports
          path: '**/coverage/'
          retention-days: 7

  build:
    name: Build
    runs-on: ubuntu-latest
    needs: [lint-typecheck, test]
    steps:
      - uses: actions/checkout@v4

      - uses: pnpm/action-setup@v4
        with:
          version: 9

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: 'pnpm'

      - run: pnpm install --frozen-lockfile

      - run: pnpm turbo run build --concurrency=3

      - uses: actions/upload-artifact@v4
        with:
          name: build-outputs
          path: |
            apps/*/dist/
            apps/*/.next/
            packages/*/dist/
          retention-days: 3

策略5:Changeset多套件發布

// .changeset/config.json
{
  "$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json",
  "changelog": "@changesets/cli/changelog",
  "commit": false,
  "fixed": [["@my-org/ui", "@my-org/utils"]],
  "linked": [["@my-org/ui", "@my-org/utils"]],
  "access": "public",
  "baseBranch": "main",
  "updateInternalDependencies": "patch",
  "ignore": ["@my-org/web", "@my-org/docs"]
}
# .github/workflows/release.yml
name: Release

on:
  push:
    branches: [main]

concurrency: ${{ github.workflow }}-${{ github.ref }}

env:
  TURBO_API: ${{ vars.TURBO_API }}
  TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
  TURBO_TEAM: ${{ vars.TURBO_TEAM }}
  NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

jobs:
  release:
    name: Release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: pnpm/action-setup@v4
        with:
          version: 9

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: 'pnpm'
          registry-url: 'https://registry.npmjs.org'

      - run: pnpm install --frozen-lockfile

      - run: pnpm turbo run build --filter=./packages/*

      - name: Create Release Pull Request or Publish
        id: changesets
        uses: changesets/action@v1
        with:
          publish: pnpm changeset publish
          version: pnpm changeset version
          title: "chore: version packages"
          commit: "chore: version packages"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

策略6:TypeScript專案引用與增量編譯

// tsconfig.base.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "composite": true,
    "incremental": true
  }
}
// packages/utils/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist", "**/*.test.ts"]
}
// apps/web/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "jsx": "preserve",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "noEmit": true,
    "incremental": true,
    "paths": {
      "@my-org/ui": ["../../packages/ui/src"],
      "@my-org/utils": ["../../packages/utils/src"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"],
  "references": [
    { "path": "../../packages/ui" },
    { "path": "../../packages/utils" }
  ]
}

避坑指南

坑1:workspace:*發布時未替換

// ❌ 錯誤:發布時workspace:*原樣發布到npm
{
  "dependencies": {
    "@my-org/utils": "workspace:*"
  }
}

// ✅ 正確:pnpm publish自動替換,但需確認pnpm版本>=8
// pnpm會自動將workspace:*替換為實際版本號

坑2:turbo.json缺少^build依賴

// ❌ 錯誤:build不依賴上游套件的build
{
  "tasks": {
    "build": {
      "dependsOn": ["build"]
    }
  }
}

// ✅ 正確:^build表示先等依賴套件build完成
{
  "tasks": {
    "build": {
      "dependsOn": ["^build"]
    }
  }
}

坑3:CI中未設定快取命中

# ❌ 錯誤:每次CI全量建構
- run: pnpm turbo run build

# ✅ 正確:設定遠端快取 + 凍結鎖檔案
- run: pnpm install --frozen-lockfile
- run: pnpm turbo run build
  env:
    TURBO_API: ${{ vars.TURBO_API }}
    TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
    TURBO_TEAM: ${{ vars.TURBO_TEAM }}

坑4:tsup未生成dts檔案

// ❌ 錯誤:只輸出JS,沒有型別宣告
{
  "scripts": {
    "build": "tsup src/index.ts --format cjs,esm"
  }
}

// ✅ 正確:新增--dts生成.d.ts檔案
{
  "scripts": {
    "build": "tsup src/index.ts --format cjs,esm --dts"
  }
}

坑5:Changeset忽略私有套件

// ❌ 錯誤:私有應用套件也參與changeset發布
{
  "ignore": []
}

// ✅ 正確:私有應用套件不需要發布到npm,應忽略
{
  "ignore": ["@my-org/web", "@my-org/docs", "@my-org/admin"]
}

報錯排查

序號 報錯訊息 原因 解決方法
1 ERR_PNPM_PEER_DEP_ISSUES peer依賴版本衝突 在package.json中設定pnpm.peerDependencyRules.allowedVersions
2 turbo: no tasks found turbo.json未設定或套件無對應script 確認turbo.json存在且套件有對應script
3 ERR_PNPM_WORKSPACE_PKG_NOT_FOUND workspace:*引用的套件不存在 檢查pnpm-workspace.yaml和套件的name欄位
4 Type error: Cannot find module '@my-org/utils' TypeScript路徑對映未設定 在tsconfig.json中設定paths和references
5 turbo cache miss 快取key變化或遠端快取未設定 檢查inputs/outputs設定,設定TURBO_API
6 npm ERR! 403 Forbidden npm發布權限不足 確認NPM_TOKEN有效且套件scope已設定
7 Changeset: No changeset files found 未建立changeset檔案 執行pnpm changeset建立變更描述
8 ERR_PNPM_LOCKFILE_MISSING pnpm-lock.yaml缺失 執行pnpm install生成鎖檔案
9 turbo: task "build" failed in "@my-org/ui" 依賴套件建構失敗 先單獨建構失敗套件:pnpm turbo run build --filter=@my-org/ui
10 ESLint: Cannot read config file ESLint設定在monorepo中路徑錯誤 使用@my-org/eslint-config統一設定

進階最佳化

1. Turborepo過濾器精準執行

# 只建構變更的套件及其依賴者
pnpm turbo run build --filter=...[HEAD^1]

# 只建構特定套件
pnpm turbo run build --filter=@my-org/ui

# 建構除指定套件外的所有套件
pnpm turbo run build --filter=!@my-org/web

# 建構依賴了@my-org/utils的所有套件
pnpm turbo run build --filter=...@my-org/utils

# 組合過濾:建構apps下變更的套件
pnpm turbo run build --filter=./apps/*[HEAD^1]

2. 共享ESLint和TypeScript設定

// packages/eslint-config/package.json
{
  "name": "@my-org/eslint-config",
  "version": "1.0.0",
  "main": "index.js",
  "dependencies": {
    "@typescript-eslint/eslint-plugin": "^8.0.0",
    "@typescript-eslint/parser": "^8.0.0",
    "eslint-config-next": "^15.0.0",
    "eslint-plugin-react": "^7.37.0",
    "eslint-plugin-react-hooks": "^5.0.0"
  }
}
// packages/eslint-config/index.js
module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
  ],
  rules: {
    '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-explicit-any': 'warn',
    'no-console': ['warn', { allow: ['warn', 'error'] }],
  },
  overrides: [
    {
      files: ['**/*.tsx'],
      extends: ['plugin:react/recommended', 'plugin:react-hooks/recommended'],
      settings: {
        react: { version: 'detect' },
      },
    },
  ],
};

3. Monorepo健康度監控

// scripts/monorepo-health.ts
import { execSync } from 'child_process';
import { readFileSync, existsSync } from 'fs';
import { join } from 'path';

interface PackageHealth {
  name: string;
  hasReadme: boolean;
  hasTests: boolean;
  hasBuildScript: boolean;
  outdatedDeps: number;
  typeCheckPass: boolean;
}

function checkMonorepoHealth(): PackageHealth[] {
  const workspaces = execSync('pnpm ls -r --depth 0 --json', { encoding: 'utf-8' });
  const packages = JSON.parse(workspaces);

  return packages.map((pkg: any) => {
    const pkgDir = pkg.path;
    const pkgJson = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf-8'));

    return {
      name: pkg.name,
      hasReadme: existsSync(join(pkgDir, 'README.md')),
      hasTests: existsSync(join(pkgDir, 'test')) || existsSync(join(pkgDir, '__tests__')),
      hasBuildScript: 'build' in (pkgJson.scripts || {}),
      outdatedDeps: 0,
      typeCheckPass: true,
    };
  });
}

const health = checkMonorepoHealth();
console.table(health);

對比分析

維度 Turborepo + pnpm Nx Lerna Rush pnpm only
學習曲線 ⭐低 ⭐⭐⭐高 ⭐⭐中 ⭐⭐⭐高 ⭐低
增量建構 ✅內建 ✅內建 ❌需設定 ✅內建
遠端快取 ✅Vercel/自託管 ✅Nx Cloud ✅BuildCache
任務編排 ✅Pipeline ✅極強 ⚠️基礎
套件發布 ⚠️需Changeset ✅內建 ✅內建 ✅內建
依賴管理 ✅pnpm ✅pnpm/npm/yarn ⚠️npm/yarn ✅pnpm ✅pnpm
維護狀態 ✅活躍 ✅活躍 ❌停止維護 ✅活躍 ✅活躍
生態整合 ⭐Next.js優先 ⭐Angular優先 ⭐通用 ⭐通用 ⭐通用

總結:Turborepo不是「又一個Monorepo工具」,而是「建構快取的革命」。它的核心價值不在於任務編排(pnpm -r也能做),而在於智慧快取——本地快取讓開發者不用重複建構,遠端快取讓CI不用重複建構,--filter讓只建構該建構的。2026年的Monorepo選型:小團隊用Turborepo + pnpm(零設定開箱即用),大團隊用Nx(更強的程式碼生成和依賴圖分析),不要用Lerna(已停止維護)。


線上工具推薦

本站提供瀏覽器本地工具,免註冊即可試用 →

#TypeScript#Monorepo#Turborepo#pnpm#CI/CD#2026#前端工程化