turborepo
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTurborepo Skill
Turborepo 技能指南
Turborepo is a high-performance build system optimized for JavaScript and TypeScript monorepos, written in Rust. It provides intelligent caching, task orchestration, and remote execution capabilities to dramatically speed up development workflows.
Turborepo 是一款为 JavaScript 和 TypeScript monorepo 优化的高性能构建系统,由 Rust 编写。它提供智能缓存、任务编排和远程执行能力,可大幅提升开发工作流的速度。
Reference
参考链接
When to Use This Skill
适用场景
Use this skill when:
- Setting up a new monorepo with multiple packages
- Optimizing build performance in existing monorepos
- Implementing task pipelines across packages
- Configuring intelligent caching strategies
- Setting up remote caching for teams
- Orchestrating tasks with dependency awareness
- Integrating monorepo with CI/CD pipelines
- Migrating from Lerna, Nx, or other monorepo tools
- Building microfrontends or shared libraries
- Managing workspace dependencies
在以下场景中使用本技能:
- 搭建包含多个包的新 monorepo
- 优化现有 monorepo 的构建性能
- 实现跨包的任务流水线
- 配置智能缓存策略
- 为团队搭建远程缓存
- 基于依赖关系编排任务
- 将 monorepo 与 CI/CD 流水线集成
- 从 Lerna、Nx 或其他 monorepo 工具迁移
- 构建微前端或共享库
- 管理工作区依赖
Core Concepts
核心概念
1. Monorepo Architecture
1. Monorepo 架构
Turborepo organizes code into packages within a single repository:
- Root Package: Contains workspace configuration
- Internal Packages: Shared libraries, utilities, configs
- Applications: Frontend apps, backend services, etc.
- Workspaces: npm/yarn/pnpm workspace configuration
Turborepo 将代码组织为单个仓库中的多个包:
- 根包(Root Package):包含工作区配置
- 内部包(Internal Packages):共享库、工具函数、配置文件
- 应用包(Applications):前端应用、后端服务等
- 工作区(Workspaces):npm/yarn/pnpm 工作区配置
2. Task Pipeline
2. 任务流水线
Tasks are organized in a dependency graph:
- Task Dependencies: Define execution order (build before test)
- Package Dependencies: Respect internal package relationships
- Parallel Execution: Run independent tasks simultaneously
- Topological Ordering: Execute tasks in correct dependency order
任务按依赖关系图组织:
- 任务依赖:定义执行顺序(如构建在测试之前)
- 包依赖:遵循内部包的关联关系
- 并行执行:同时运行独立任务
- 拓扑排序:按正确的依赖顺序执行任务
3. Intelligent Caching
3. 智能缓存
Turborepo caches task outputs based on inputs:
- Local Cache: Stores outputs on local machine
- Remote Cache: Shares cache across team/CI (Vercel or custom)
- Content-Based Hashing: Only re-run when inputs change
- Cache Restoration: Instant task completion from cache
Turborepo 根据输入内容缓存任务输出:
- 本地缓存:将输出存储在本地机器
- 远程缓存:在团队/CI 间共享缓存(支持 Vercel 或自定义服务)
- 基于内容的哈希:仅当输入变化时才重新执行任务
- 缓存恢复:从缓存中直接完成任务,实现即时执行
4. Task Outputs
4. 任务输出
Define what gets cached:
- Build artifacts (dist/, build/)
- Test results
- Generated files
- Type definitions
定义需要缓存的内容:
- 构建产物(dist/、build/)
- 测试结果
- 生成的文件
- 类型定义文件
Installation
安装步骤
Prerequisites
前置要求
bash
undefinedbash
undefinedRequires Node.js 18+ and a package manager
需要 Node.js 18+ 和包管理器
node --version # v18.0.0+
undefinednode --version # v18.0.0+
undefinedGlobal Installation
全局安装
bash
undefinedbash
undefinednpm
npm
npm install turbo --global
npm install turbo --global
yarn
yarn
yarn global add turbo
yarn global add turbo
pnpm
pnpm
pnpm add turbo --global
pnpm add turbo --global
bun
bun
bun add turbo --global
undefinedbun add turbo --global
undefinedPer-Project Installation
按项目安装
bash
undefinedbash
undefinednpm
npm
npm install turbo --save-dev
npm install turbo --save-dev
yarn
yarn
yarn add turbo --dev
yarn add turbo --dev
pnpm
pnpm
pnpm add turbo --save-dev
pnpm add turbo --save-dev
bun
bun
bun add turbo --dev
undefinedbun add turbo --dev
undefinedProject Setup
项目搭建
Create New Monorepo
创建新的 Monorepo
Using official examples:
bash
npx create-turbo@latestInteractive prompts will ask:
- Project name
- Package manager (npm/yarn/pnpm/bun)
- Example template selection
使用官方示例:
bash
npx create-turbo@latest交互式提示将询问:
- 项目名称
- 包管理器(npm/yarn/pnpm/bun)
- 示例模板选择
Manual Setup
手动搭建
1. Initialize workspace:
json
// package.json (root)
{
"name": "my-turborepo",
"private": true,
"workspaces": ["apps/*", "packages/*"],
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev",
"test": "turbo run test",
"lint": "turbo run lint"
},
"devDependencies": {
"turbo": "latest"
}
}2. Create directory structure:
my-turborepo/
├── apps/
│ ├── web/ # Next.js app
│ └── docs/ # Documentation site
├── packages/
│ ├── ui/ # Shared UI components
│ ├── config/ # Shared configs (ESLint, TS)
│ └── tsconfig/ # Shared TypeScript configs
├── turbo.json # Turborepo configuration
└── package.json # Root package.json3. Create turbo.json:
json
{
"$schema": "https://turbo.build/schema.json",
"globalDependencies": ["**/.env.*local"],
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": [".next/**", "!.next/cache/**", "dist/**"]
},
"dev": {
"cache": false,
"persistent": true
},
"lint": {},
"test": {
"dependsOn": ["build"]
}
}
}1. 初始化工作区:
json
// package.json (根目录)
{
"name": "my-turborepo",
"private": true,
"workspaces": ["apps/*", "packages/*"],
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev",
"test": "turbo run test",
"lint": "turbo run lint"
},
"devDependencies": {
"turbo": "latest"
}
}2. 创建目录结构:
my-turborepo/
├── apps/
│ ├── web/ # Next.js 应用
│ └── docs/ # 文档站点
├── packages/
│ ├── ui/ # 共享 UI 组件
│ ├── config/ # 共享配置(ESLint、TS)
│ └── tsconfig/ # 共享 TypeScript 配置
├── turbo.json # Turborepo 配置文件
└── package.json # 根目录 package.json3. 创建 turbo.json:
json
{
"$schema": "https://turbo.build/schema.json",
"globalDependencies": ["**/.env.*local"],
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": [".next/**", "!.next/cache/**", "dist/**"]
},
"dev": {
"cache": false,
"persistent": true
},
"lint": {},
"test": {
"dependsOn": ["build"]
}
}
}Configuration (turbo.json)
配置(turbo.json)
Basic Structure
基础结构
json
{
"$schema": "https://turbo.build/schema.json",
"globalDependencies": [".env", "tsconfig.json"],
"globalEnv": ["NODE_ENV"],
"pipeline": {
// Task definitions
}
}json
{
"$schema": "https://turbo.build/schema.json",
"globalDependencies": [".env", "tsconfig.json"],
"globalEnv": ["NODE_ENV"],
"pipeline": {
// 任务定义
}
}Pipeline Configuration
流水线配置
Task with dependencies:
json
{
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", ".next/**"],
"env": ["NODE_ENV", "API_URL"]
}
}
}Key properties:
- : Tasks to run first
dependsOn- : Run dependencies' build first
["^build"] - : Run own build first
["build"] - : Run deps' build and own lint
["^build", "lint"]
- : Files/directories to cache
outputs - : Override input detection (default: all tracked files)
inputs - : Enable/disable caching (default: true)
cache - : Environment variables that affect output
env - : Keep task running (for dev servers)
persistent - : Control output display
outputMode
带依赖的任务:
json
{
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", ".next/**"],
"env": ["NODE_ENV", "API_URL"]
}
}
}关键属性:
- :需要先执行的任务
dependsOn- :先执行依赖包的 build 任务
["^build"] - :先执行自身的 build 任务
["build"] - :先执行依赖包的 build 任务和自身的 lint 任务
["^build", "lint"]
- :需要缓存的文件/目录
outputs - :覆盖默认的输入检测(默认:所有被追踪的文件)
inputs - :启用/禁用缓存(默认:true)
cache - :会影响输出结果的环境变量
env - :保持任务持续运行(适用于开发服务器)
persistent - :控制输出显示方式
outputMode
Task Dependency Patterns
任务依赖模式
Topological (^):
json
{
"build": {
"dependsOn": ["^build"] // Run dependencies' build first
}
}Regular:
json
{
"deploy": {
"dependsOn": ["build", "test"] // Run own build and test first
}
}Combined:
json
{
"test": {
"dependsOn": ["^build", "lint"] // Deps' build, then own lint
}
}拓扑依赖(^):
json
{
"build": {
"dependsOn": ["^build"] // 先执行依赖包的 build 任务
}
}常规依赖:
json
{
"deploy": {
"dependsOn": ["build", "test"] // 先执行自身的 build 和 test 任务
}
}组合依赖:
json
{
"test": {
"dependsOn": ["^build", "lint"] // 先执行依赖包的 build 任务,再执行自身的 lint 任务
}
}Output Modes
输出模式
json
{
"pipeline": {
"build": {
"outputMode": "full" // Show all output
},
"dev": {
"outputMode": "hash-only" // Show cache hash only
},
"test": {
"outputMode": "new-only" // Show new output only
},
"lint": {
"outputMode": "errors-only" // Show errors only
}
}
}json
{
"pipeline": {
"build": {
"outputMode": "full" // 显示所有输出
},
"dev": {
"outputMode": "hash-only" // 仅显示缓存哈希
},
"test": {
"outputMode": "new-only" // 仅显示新输出
},
"lint": {
"outputMode": "errors-only" // 仅显示错误
}
}
}Environment Variables
环境变量
Global environment variables:
json
{
"globalEnv": ["NODE_ENV", "CI"],
"globalDependencies": [".env", ".env.local"]
}Per-task environment variables:
json
{
"pipeline": {
"build": {
"env": ["NEXT_PUBLIC_API_URL", "DATABASE_URL"],
"passThroughEnv": ["CUSTOM_VAR"] // Pass without hashing
}
}
}全局环境变量:
json
{
"globalEnv": ["NODE_ENV", "CI"],
"globalDependencies": [".env", ".env.local"]
}按任务配置的环境变量:
json
{
"pipeline": {
"build": {
"env": ["NEXT_PUBLIC_API_URL", "DATABASE_URL"],
"passThroughEnv": ["CUSTOM_VAR"] // 传递但不参与哈希计算
}
}
}Commands
命令说明
turbo run
turbo run
Run tasks across packages:
bash
undefined跨包运行任务:
bash
undefinedRun build in all packages
在所有包中运行 build 任务
turbo run build
turbo run build
Run multiple tasks
运行多个任务
turbo run build test lint
turbo run build test lint
Run in specific packages
在指定包中运行任务
turbo run build --filter=web
turbo run build --filter=@myorg/ui
turbo run build --filter=web
turbo run build --filter=@myorg/ui
Run in packages matching pattern
在匹配模式的包中运行任务
turbo run build --filter='./apps/*'
turbo run build --filter='./apps/*'
Force execution (skip cache)
强制执行(跳过缓存)
turbo run build --force
turbo run build --force
Run from specific directory
从指定目录运行任务
turbo run build --filter='[./apps/web]'
turbo run build --filter='[./apps/web]'
Run with dependencies
运行包含依赖的任务
turbo run build --filter='...^web'
turbo run build --filter='...^web'
Parallel execution control
控制并行执行数量
turbo run build --concurrency=3
turbo run build --concurrency=50%
turbo run build --concurrency=3
turbo run build --concurrency=50%
Continue on error
出错后继续执行
turbo run test --continue
turbo run test --continue
Dry run
模拟运行(不实际执行)
turbo run build --dry-run
turbo run build --dry-run
Output control
控制输出日志
turbo run build --output-logs=new-only
turbo run build --output-logs=hash-only
turbo run build --output-logs=errors-only
turbo run build --output-logs=full
undefinedturbo run build --output-logs=new-only
turbo run build --output-logs=hash-only
turbo run build --output-logs=errors-only
turbo run build --output-logs=full
undefinedturbo prune
turbo prune
Create a subset of the monorepo:
bash
undefined创建 monorepo 的子集:
bash
undefinedPrune for specific app
为指定应用裁剪代码
turbo prune --scope=web
turbo prune --scope=web
Prune with Docker
为 Docker 构建裁剪代码
turbo prune --scope=api --docker
turbo prune --scope=api --docker
Output to custom directory
将输出保存到自定义目录
turbo prune --scope=web --out-dir=./deploy
**Use cases:**
- Docker builds (only include necessary packages)
- Deploy specific apps
- Reduce CI/CD context sizeturbo prune --scope=web --out-dir=./deploy
**适用场景:**
- Docker 构建(仅包含必要的包)
- 部署指定应用
- 减小 CI/CD 的上下文大小turbo gen
turbo gen
Generate code in your monorepo:
bash
undefined在 monorepo 中生成代码:
bash
undefinedGenerate new package
生成新的包
turbo gen workspace
turbo gen workspace
Generate from custom generator
使用自定义生成器生成代码
turbo gen my-generator
turbo gen my-generator
List available generators
列出可用的生成器
turbo gen --list
undefinedturbo gen --list
undefinedturbo link
turbo link
Link local repo to remote cache:
bash
undefined将本地仓库链接到远程缓存:
bash
undefinedLink to Vercel
链接到 Vercel
turbo link
turbo link
Unlink
取消链接
turbo unlink
undefinedturbo unlink
undefinedturbo login
turbo login
Authenticate with Vercel:
bash
turbo login通过 Vercel 认证:
bash
turbo loginturbo ls
turbo ls
List packages in monorepo:
bash
undefined列出 monorepo 中的所有包:
bash
undefinedList all packages
列出所有包
turbo ls
turbo ls
JSON output
以 JSON 格式输出
turbo ls --json
undefinedturbo ls --json
undefinedFiltering
过滤功能
Filter by Package Name
按包名过滤
bash
undefinedbash
undefinedSingle package
单个包
turbo run build --filter=web
turbo run build --filter=web
Multiple packages
多个包
turbo run build --filter=web --filter=api
turbo run build --filter=web --filter=api
Scoped package
带作用域的包
turbo run build --filter=@myorg/ui
undefinedturbo run build --filter=@myorg/ui
undefinedFilter by Pattern
按模式过滤
bash
undefinedbash
undefinedAll apps
所有应用包
turbo run build --filter='./apps/*'
turbo run build --filter='./apps/*'
Pattern matching
匹配模式的包
turbo run build --filter='*-ui'
undefinedturbo run build --filter='*-ui'
undefinedFilter by Directory
按目录过滤
bash
undefinedbash
undefinedFrom specific directory
从指定目录运行
turbo run build --filter='[./apps/web]'
undefinedturbo run build --filter='[./apps/web]'
undefinedFilter by Git
按 Git 变更过滤
bash
undefinedbash
undefinedChanged since main
自 main 分支以来变更的包
turbo run build --filter='[main]'
turbo run build --filter='[main]'
Changed since HEAD~1
自 HEAD~1 以来变更的包
turbo run build --filter='[HEAD~1]'
turbo run build --filter='[HEAD~1]'
Changed in working directory
工作目录中变更的包
turbo run test --filter='...[HEAD]'
undefinedturbo run test --filter='...[HEAD]'
undefinedFilter by Dependencies
按依赖关系过滤
bash
undefinedbash
undefinedPackage and its dependencies
包及其依赖包
turbo run build --filter='...web'
turbo run build --filter='...web'
Package's dependencies only
仅包的依赖包
turbo run build --filter='...^web'
turbo run build --filter='...^web'
Package and its dependents
包及其依赖它的包
turbo run test --filter='ui...'
turbo run test --filter='ui...'
Package's dependents only
仅依赖该包的包
turbo run test --filter='^ui...'
undefinedturbo run test --filter='^ui...'
undefinedCaching Strategies
缓存策略
Local Caching
本地缓存
Enabled by default, stores in
./node_modules/.cache/turboCache behavior:
json
{
"pipeline": {
"build": {
"outputs": ["dist/**"], // Cache dist directory
"cache": true // Enable caching (default)
},
"dev": {
"cache": false // Disable for dev servers
}
}
}Clear cache:
bash
undefined默认启用,存储在
./node_modules/.cache/turbo缓存行为配置:
json
{
"pipeline": {
"build": {
"outputs": ["dist/**"], // 缓存 dist 目录
"cache": true // 启用缓存(默认值)
},
"dev": {
"cache": false // 开发服务器禁用缓存
}
}
}清除缓存:
bash
undefinedClear Turbo cache
清除 Turbo 缓存
rm -rf ./node_modules/.cache/turbo
rm -rf ./node_modules/.cache/turbo
Or use turbo command
或使用 Turbo 命令强制重建
turbo run build --force # Skip cache for this run
undefinedturbo run build --force
undefinedRemote Caching
远程缓存
Share cache across team and CI:
1. Link to Vercel (recommended):
bash
turbo login
turbo link2. Custom remote cache:
json
// .turbo/config.json
{
"teamid": "team_123",
"apiurl": "https://cache.example.com",
"token": "your-token"
}Benefits:
- Share builds across team
- Speed up CI/CD
- Consistent builds
- Reduce compute costs
在团队和 CI 间共享缓存:
1. 链接到 Vercel(推荐):
bash
turbo login
turbo link2. 自定义远程缓存:
json
// .turbo/config.json
{
"teamid": "team_123",
"apiurl": "https://cache.example.com",
"token": "your-token"
}优势:
- 团队间共享构建结果
- 加速 CI/CD 流程
- 构建结果一致性
- 降低计算成本
Cache Signatures
缓存签名
Cache is invalidated when:
- Source files change
- Dependencies change
- Environment variables change (if specified)
- Global dependencies change
- Task configuration changes
Control inputs:
json
{
"pipeline": {
"build": {
"inputs": ["src/**/*.ts", "!src/**/*.test.ts"],
"env": ["NODE_ENV"]
}
}
}当以下内容变更时,缓存会失效:
- 源文件变更
- 依赖包变更
- 环境变量变更(如果已配置)
- 全局依赖变更
- 任务配置变更
控制输入内容:
json
{
"pipeline": {
"build": {
"inputs": ["src/**/*.ts", "!src/**/*.test.ts"],
"env": ["NODE_ENV"]
}
}
}Workspace Patterns
工作区模式
Package Types
包类型
1. Internal packages (packages/*):
json
// packages/ui/package.json
{
"name": "@myorg/ui",
"version": "0.0.0",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"lint": "eslint ."
}
}2. Applications (apps/*):
json
// apps/web/package.json
{
"name": "web",
"version": "1.0.0",
"private": true,
"dependencies": {
"@myorg/ui": "*",
"next": "latest"
},
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
}
}1. 内部包(packages/*):
json
// packages/ui/package.json
{
"name": "@myorg/ui",
"version": "0.0.0",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"lint": "eslint ."
}
}2. 应用包(apps/*):
json
// apps/web/package.json
{
"name": "web",
"version": "1.0.0",
"private": true,
"dependencies": {
"@myorg/ui": "*",
"next": "latest"
},
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
}
}Dependency Management
依赖管理
Workspace protocol (pnpm/yarn):
json
{
"dependencies": {
"@myorg/ui": "workspace:*"
}
}Version protocol (npm):
json
{
"dependencies": {
"@myorg/ui": "*"
}
}工作区协议(pnpm/yarn):
json
{
"dependencies": {
"@myorg/ui": "workspace:*"
}
}版本协议(npm):
json
{
"dependencies": {
"@myorg/ui": "*"
}
}Shared Configuration
共享配置
ESLint config package:
js
// packages/eslint-config/index.js
module.exports = {
extends: ["next", "prettier"],
rules: {
// shared rules
},
};TypeScript config package:
json
// packages/tsconfig/base.json
{
"compilerOptions": {
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}Usage:
json
// apps/web/tsconfig.json
{
"extends": "@myorg/tsconfig/base.json",
"compilerOptions": {
"jsx": "preserve"
}
}ESLint 配置包:
js
// packages/eslint-config/index.js
module.exports = {
extends: ["next", "prettier"],
rules: {
// 共享规则
},
};TypeScript 配置包:
json
// packages/tsconfig/base.json
{
"compilerOptions": {
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}使用方式:
json
// apps/web/tsconfig.json
{
"extends": "@myorg/tsconfig/base.json",
"compilerOptions": {
"jsx": "preserve"
}
}CI/CD Integration
CI/CD 集成
GitHub Actions
GitHub Actions
yaml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
- name: Install dependencies
run: npm install
- name: Build
run: npx turbo run build
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
- name: Test
run: npx turbo run testyaml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
- name: 安装依赖
run: npm install
- name: 构建
run: npx turbo run build
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
- name: 测试
run: npx turbo run testGitLab CI
GitLab CI
yaml
image: node:18
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
- .turbo/
build:
stage: build
script:
- npm install
- npx turbo run build
variables:
TURBO_TOKEN: $TURBO_TOKEN
TURBO_TEAM: $TURBO_TEAMyaml
image: node:18
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules/
- .turbo/
build:
stage: build
script:
- npm install
- npx turbo run build
variables:
TURBO_TOKEN: $TURBO_TOKEN
TURBO_TEAM: $TURBO_TEAMDocker
Docker
dockerfile
FROM node:18-alpine AS basedockerfile
FROM node:18-alpine AS basePrune workspace
裁剪工作区
FROM base AS builder
RUN npm install -g turbo
COPY . .
RUN turbo prune --scope=web --docker
FROM base AS builder
RUN npm install -g turbo
COPY . .
RUN turbo prune --scope=web --docker
Install dependencies
安装依赖
FROM base AS installer
COPY --from=builder /app/out/json/ .
COPY --from=builder /app/out/package-lock.json ./package-lock.json
RUN npm install
FROM base AS installer
COPY --from=builder /app/out/json/ .
COPY --from=builder /app/out/package-lock.json ./package-lock.json
RUN npm install
Build
构建应用
COPY --from=builder /app/out/full/ .
RUN npx turbo run build --filter=web
COPY --from=builder /app/out/full/ .
RUN npx turbo run build --filter=web
Runner
运行阶段
FROM base AS runner
COPY --from=installer /app/apps/web/.next/standalone ./
COPY --from=installer /app/apps/web/.next/static ./apps/web/.next/static
COPY --from=installer /app/apps/web/public ./apps/web/public
CMD node apps/web/server.js
undefinedFROM base AS runner
COPY --from=installer /app/apps/web/.next/standalone ./
COPY --from=installer /app/apps/web/.next/static ./apps/web/.next/static
COPY --from=installer /app/apps/web/public ./apps/web/public
CMD node apps/web/server.js
undefinedOptimization Tips
优化技巧
- Use remote caching in CI:
yaml
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}- Cache node_modules:
yaml
- uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}- Run only affected tasks:
bash
turbo run build test --filter='...[origin/main]'- 在 CI 中启用远程缓存:
yaml
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}- 缓存 node_modules:
yaml
- uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}- 仅运行受影响的任务:
bash
turbo run build test --filter='...[origin/main]'Framework Integration
框架集成
Next.js
Next.js
json
// apps/web/package.json
{
"name": "web",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "latest"
}
}turbo.json:
json
{
"pipeline": {
"build": {
"outputs": [".next/**", "!.next/cache/**"]
},
"dev": {
"cache": false,
"persistent": true
}
}
}json
// apps/web/package.json
{
"name": "web",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "latest"
}
}turbo.json 配置:
json
{
"pipeline": {
"build": {
"outputs": [".next/**", "!.next/cache/**"]
},
"dev": {
"cache": false,
"persistent": true
}
}
}Vite
Vite
json
{
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
},
"dev": {
"cache": false,
"persistent": true
}
}
}json
{
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
},
"dev": {
"cache": false,
"persistent": true
}
}
}NuxtJS
NuxtJS
json
{
"pipeline": {
"build": {
"outputs": [".output/**", ".nuxt/**"]
},
"dev": {
"cache": false,
"persistent": true
}
}
}json
{
"pipeline": {
"build": {
"outputs": [".output/**", ".nuxt/**"]
},
"dev": {
"cache": false,
"persistent": true
}
}
}Development Tools Integration
开发工具集成
TypeScript
TypeScript
json
{
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", "*.tsbuildinfo"]
},
"typecheck": {
"dependsOn": ["^build"]
}
}
}json
{
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", "*.tsbuildinfo"]
},
"typecheck": {
"dependsOn": ["^build"]
}
}
}ESLint
ESLint
json
{
"pipeline": {
"lint": {
"dependsOn": ["^build"],
"outputs": []
}
}
}json
{
"pipeline": {
"lint": {
"dependsOn": ["^build"],
"outputs": []
}
}
}Jest / Vitest
Jest / Vitest
json
{
"pipeline": {
"test": {
"dependsOn": ["build"],
"outputs": ["coverage/**"],
"cache": true
}
}
}json
{
"pipeline": {
"test": {
"dependsOn": ["build"],
"outputs": ["coverage/**"],
"cache": true
}
}
}Prisma
Prisma
json
{
"pipeline": {
"db:generate": {
"cache": false
},
"db:push": {
"cache": false
}
}
}json
{
"pipeline": {
"db:generate": {
"cache": false
},
"db:push": {
"cache": false
}
}
}Best Practices
最佳实践
1. Structure Your Monorepo
1. 合理组织 Monorepo 结构
my-monorepo/
├── apps/ # Applications
│ ├── web/ # Frontend app
│ ├── api/ # Backend API
│ └── docs/ # Documentation
├── packages/ # Shared packages
│ ├── ui/ # UI components
│ ├── config/ # Shared configs
│ ├── utils/ # Utilities
│ └── tsconfig/ # TS configs
├── tooling/ # Development tools
│ ├── eslint-config/
│ └── prettier-config/
└── turbo.jsonmy-monorepo/
├── apps/ # 应用包
│ ├── web/ # 前端应用
│ ├── api/ # 后端 API
│ └── docs/ # 文档站点
├── packages/ # 共享包
│ ├── ui/ # UI 组件
│ ├── config/ # 共享配置
│ ├── utils/ # 工具函数
│ └── tsconfig/ # TypeScript 配置
├── tooling/ # 开发工具
│ ├── eslint-config/
│ └── prettier-config/
└── turbo.json2. Define Clear Task Dependencies
2. 清晰定义任务依赖
json
{
"pipeline": {
"build": {
"dependsOn": ["^build"]
},
"test": {
"dependsOn": ["build"]
},
"lint": {
"dependsOn": ["^build"]
},
"deploy": {
"dependsOn": ["build", "test", "lint"]
}
}
}json
{
"pipeline": {
"build": {
"dependsOn": ["^build"]
},
"test": {
"dependsOn": ["build"]
},
"lint": {
"dependsOn": ["^build"]
},
"deploy": {
"dependsOn": ["build", "test", "lint"]
}
}
}3. Optimize Cache Configuration
3. 优化缓存配置
- Cache build outputs, not source files
- Include all generated files in outputs
- Exclude cache directories (e.g., )
.next/cache - Disable cache for dev servers
json
{
"pipeline": {
"build": {
"outputs": [
"dist/**",
".next/**",
"!.next/cache/**",
"storybook-static/**"
]
},
"dev": {
"cache": false,
"persistent": true
}
}
}- 缓存构建产物,而非源文件
- 将所有生成的文件加入 outputs
- 排除缓存目录(如 )
.next/cache - 为开发服务器禁用缓存
json
{
"pipeline": {
"build": {
"outputs": [
"dist/**",
".next/**",
"!.next/cache/**",
"storybook-static/**"
]
},
"dev": {
"cache": false,
"persistent": true
}
}
}4. Use Environment Variables Wisely
4. 合理使用环境变量
json
{
"globalEnv": ["NODE_ENV", "CI"],
"pipeline": {
"build": {
"env": ["NEXT_PUBLIC_API_URL"],
"passThroughEnv": ["DEBUG"] // Don't affect cache
}
}
}json
{
"globalEnv": ["NODE_ENV", "CI"],
"pipeline": {
"build": {
"env": ["NEXT_PUBLIC_API_URL"],
"passThroughEnv": ["DEBUG"] // 不影响缓存
}
}
}5. Leverage Remote Caching
5. 充分利用远程缓存
- Enable for all team members
- Configure in CI/CD
- Reduces build times significantly
- Especially beneficial for large teams
- 为所有团队成员启用
- 在 CI/CD 中配置
- 可显著减少构建时间
- 对大型团队尤其有益
6. Use Filters Effectively
6. 高效使用过滤功能
bash
undefinedbash
undefinedBuild only changed packages
仅构建变更的包
turbo run build --filter='...[origin/main]'
turbo run build --filter='...[origin/main]'
Build specific app with dependencies
构建指定应用及其依赖
turbo run build --filter='...web'
turbo run build --filter='...web'
Test only affected packages
仅测试受影响的包
turbo run test --filter='...[HEAD^1]'
undefinedturbo run test --filter='...[HEAD^1]'
undefined7. Organize Scripts Consistently
7. 保持脚本命名一致
Root package.json:
json
{
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev",
"lint": "turbo run lint",
"test": "turbo run test",
"clean": "turbo run clean && rm -rf node_modules"
}
}根目录 package.json:
json
{
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev",
"lint": "turbo run lint",
"test": "turbo run test",
"clean": "turbo run clean && rm -rf node_modules"
}
}8. Handle Persistent Tasks
8. 处理持久化任务
json
{
"pipeline": {
"dev": {
"cache": false,
"persistent": true // Keeps running
}
}
}json
{
"pipeline": {
"dev": {
"cache": false,
"persistent": true // 保持任务持续运行
}
}
}Common Patterns
常见模式
Full-Stack Application
全栈应用
apps/
├── web/ # Next.js frontend
│ └── package.json
├── api/ # Express backend
│ └── package.json
└── mobile/ # React Native
└── package.json
packages/
├── ui/ # Shared UI components
├── database/ # Database client/migrations
├── types/ # Shared TypeScript types
└── config/ # Shared configsapps/
├── web/ # Next.js 前端
│ └── package.json
├── api/ # Express 后端
│ └── package.json
└── mobile/ # React Native 应用
└── package.json
packages/
├── ui/ # 共享 UI 组件
├── database/ # 数据库客户端/迁移
├── types/ # 共享 TypeScript 类型
└── config/ # 共享配置Shared Component Library
共享组件库
packages/
├── ui/ # Component library
│ ├── src/
│ ├── package.json
│ └── tsconfig.json
└── ui-docs/ # Storybook
├── .storybook/
├── stories/
└── package.jsonpackages/
├── ui/ # 组件库
│ ├── src/
│ ├── package.json
│ └── tsconfig.json
└── ui-docs/ # Storybook 文档
├── .storybook/
├── stories/
└── package.jsonMicrofrontends
微前端
apps/
├── shell/ # Container app
├── dashboard/ # Dashboard MFE
└── settings/ # Settings MFE
packages/
├── shared-ui/ # Shared components
└── router/ # Routing logicapps/
├── shell/ # 容器应用
├── dashboard/ # 仪表盘微前端
└── settings/ # 设置页微前端
packages/
├── shared-ui/ # 共享组件
└── router/ # 路由逻辑Troubleshooting
故障排查
Cache Issues
缓存问题
Problem: Task not using cache when it should
bash
undefined问题:任务未按预期使用缓存
bash
undefinedCheck what's causing cache miss
检查缓存失效原因
turbo run build --dry-run=json
turbo run build --dry-run=json
Force rebuild
强制重建
turbo run build --force
turbo run build --force
Clear cache
清除本地缓存
rm -rf ./node_modules/.cache/turbo
**Problem**: Cache too large
```bashrm -rf ./node_modules/.cache/turbo
**问题**:缓存体积过大
```bashLimit cache size in turbo.json
在 turbo.json 中限制缓存大小
{
"cacheDir": ".turbo",
"cacheSize": "50gb"
}
undefined{
"cacheDir": ".turbo",
"cacheSize": "50gb"
}
undefinedDependency Issues
依赖问题
Problem: Internal package not found
bash
undefined问题:找不到内部包
bash
undefinedEnsure workspace is set up correctly
确保工作区配置正确
npm install
npm install
Check package names match
检查包名是否匹配
npm ls @myorg/ui
npm ls @myorg/ui
Rebuild dependencies
重新构建依赖包
turbo run build --filter='...web'
undefinedturbo run build --filter='...web'
undefinedTask Execution Issues
任务执行问题
Problem: Tasks running in wrong order
- Check configuration
dependsOn - Use for dependency tasks
^task - Verify task names match package.json scripts
Problem: Dev server not starting
json
{
"pipeline": {
"dev": {
"cache": false,
"persistent": true // Add this
}
}
}问题:任务执行顺序错误
- 检查 配置
dependsOn - 使用 语法指定依赖包的任务
^task - 确保任务名称与 package.json 中的脚本一致
问题:开发服务器无法启动
json
{
"pipeline": {
"dev": {
"cache": false,
"persistent": true // 添加此配置
}
}
}Performance Issues
性能问题
Problem: Builds taking too long
bash
undefined问题:构建耗时过长
bash
undefinedRun with concurrency limit
限制并行执行数量
turbo run build --concurrency=2
turbo run build --concurrency=2
Use filters to build less
使用过滤功能减少构建范围
turbo run build --filter='...[origin/main]'
turbo run build --filter='...[origin/main]'
Check for unnecessary dependencies
检查不必要的依赖
turbo run build --dry-run
**Problem**: Remote cache not working
```bashturbo run build --dry-run
**问题**:远程缓存无法工作
```bashVerify authentication
验证认证状态
turbo link
turbo link
Check environment variables
检查环境变量
echo $TURBO_TOKEN
echo $TURBO_TEAM
echo $TURBO_TOKEN
echo $TURBO_TEAM
Test connection
测试连接
turbo run build --output-logs=hash-only
undefinedturbo run build --output-logs=hash-only
undefinedMigration Guide
迁移指南
From Lerna
从 Lerna 迁移
- Replace Lerna with Turborepo:
bash
npm uninstall lerna
npm install turbo --save-dev- Convert lerna.json to turbo.json:
json
{
"pipeline": {
"build": {
"dependsOn": ["^build"]
}
}
}- Update scripts:
json
{
"scripts": {
"build": "turbo run build",
"test": "turbo run test"
}
}- 替换 Lerna 为 Turborepo:
bash
npm uninstall lerna
npm install turbo --save-dev- 将 lerna.json 转换为 turbo.json:
json
{
"pipeline": {
"build": {
"dependsOn": ["^build"]
}
}
}- 更新根目录脚本:
json
{
"scripts": {
"build": "turbo run build",
"test": "turbo run test"
}
}From Nx
从 Nx 迁移
- Install Turborepo:
bash
npm install turbo --save-dev- Convert nx.json to turbo.json:
- Map targetDefaults to pipeline
- Convert dependsOn syntax
- Configure caching
- Update workspace configuration
- Migrate CI/CD scripts
- 安装 Turborepo:
bash
npm install turbo --save-dev- 将 nx.json 转换为 turbo.json:
- 将 targetDefaults 映射为 pipeline
- 转换 dependsOn 语法
- 配置缓存规则
- 更新工作区配置
- 迁移 CI/CD 脚本
Resources
参考资源
- Documentation: https://turbo.build/repo/docs
- Examples: https://github.com/vercel/turbo/tree/main/examples
- Discord: https://turbo.build/discord
- GitHub: https://github.com/vercel/turbo
Implementation Checklist
实施检查清单
When setting up Turborepo:
- Install Turborepo globally or per-project
- Set up workspace structure (apps/, packages/)
- Create turbo.json with pipeline configuration
- Define task dependencies (build, test, lint)
- Configure cache outputs for each task
- Set up global dependencies and environment variables
- Link to remote cache (Vercel or custom)
- Configure CI/CD integration
- Add filtering strategies for large repos
- Document monorepo structure for team
- Set up code generation (turbo gen)
- Configure Docker builds with turbo prune
- Test caching behavior locally
- Verify remote cache in CI
- Optimize concurrency settings
搭建 Turborepo 时,请完成以下检查:
- 全局或按项目安装 Turborepo
- 搭建工作区结构(apps/、packages/)
- 创建 turbo.json 并配置流水线
- 定义任务依赖(build、test、lint)
- 为每个任务配置缓存输出
- 设置全局依赖和环境变量
- 链接到远程缓存(Vercel 或自定义服务)
- 配置 CI/CD 集成
- 为大型仓库添加过滤策略
- 为团队文档化 monorepo 结构
- 配置代码生成(turbo gen)
- 使用 turbo prune 配置 Docker 构建
- 本地测试缓存行为
- 在 CI 中验证远程缓存
- 优化并发执行设置