关于 turborepo
用于在 JavaScript 和 TypeScript 单仓库中配置及排查 Turborepo 的技能。内容强调包级任务、依赖图编排、缓存、筛选以及常见配置问题。
主要功能
- 01在包级配置任务
- 02在 turbo.json 中注册任务
- 03利用依赖图安排顺序与并行
- 04使用缓存和受影响包筛选
- 05排查环境及配置问题
适用场景
- 01配置单仓库的构建、Lint 和测试任务
- 02仅运行发生变更的包
- 03排查缓存未命中或任务顺序问题
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ bklit/ bklit-ui --skill turborepo安装后在 Claude Code 中输入/turborepo确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
command/turborepo.mdreferences/best-practices/dependencies.mdpackages.mdstructure.mdreferences/caching/gotchas.mdremote-cache.mdreferences/ci/github-actions.mdpatterns.mdvercel.mdreferences/cli/commands.mdreferences/configuration/global-options.mdgotchas.mdtasks.mdreferences/environment/gotchas.mdmodes.mdreferences/filtering/patterns.md详细介绍
Turborepo 技能
用于 JavaScript/TypeScript 单体仓库的构建系统。Turborepo 会缓存任务输出,并根据依赖图并行运行任务。
重要:配置包任务,而非根任务
不要创建根任务。始终创建包任务。
创建任务、脚本或流水线时,必须:
- 将脚本添加到每个相关包的
package.json中 - 在根目录的
turbo.json中注册任务 - 根目录的
package.json仅通过turbo run <task>调用任务
不要将任务逻辑放在根目录的 package.json 中。这会破坏 Turborepo 的并行执行能力。
// DO THIS: Scripts in each package
// apps/web/package.json
{ "scripts": { "build": "next build", "lint": "eslint .", "test": "vitest" } }
// apps/api/package.json
{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest" } }
// packages/ui/package.json
{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest" } }
// turbo.json - register tasks
{
"tasks": {
"build": { "dependsOn": ["^build"], "outputs": ["dist/**"] },
"lint": {},
"test": { "dependsOn": ["build"] }
}
}
// Root package.json - ONLY delegates, no task logic
{
"scripts": {
"build": "turbo run build",
"lint": "turbo run lint",
"test": "turbo run test"
}
}
// DO NOT DO THIS - defeats parallelization
// Root package.json
{
"scripts": {
"build": "cd apps/web && next build && cd ../api && tsc",
"lint": "eslint apps/ packages/",
"test": "vitest"
}
}
根任务(//#taskname)仅用于确实无法放在包中的任务(很少见)。
次要规则:turbo run 与 turbo
命令写入代码时,始终使用 turbo run:
// package.json - ALWAYS "turbo run"
{
"scripts": {
"build": "turbo run build"
}
}
# CI workflows - ALWAYS "turbo run"
- run: turbo run build --affected
简写 turbo <tasks> 仅用于由人或 Agent 直接在终端中输入的一次性命令。切勿在 package.json、CI 或脚本中写入 turbo build。
快速决策树
“我需要配置任务”
Configure a task?
├─ Define task dependencies → references/configuration/tasks.md
├─ Lint/check-types (parallel + caching) → Use Transit Nodes pattern (see below)
├─ Specify build outputs → references/configuration/tasks.md#outputs
├─ Handle environment variables → references/environment/README.md
├─ Set up dev/watch tasks → references/configuration/tasks.md#persistent
├─ Package-specific config → references/configuration/README.md#package-configurations
└─ Global settings (cacheDir, daemon) → references/configuration/global-options.md
“缓存不起作用”
Cache problems?
├─ Tasks run but outputs not restored → Missing `outputs` key
├─ Cache misses unexpectedly → references/caching/gotchas.md
├─ Need to debug hash inputs → Use --summarize or --dry
├─ Want to skip cache entirely → Use --force or cache: false
├─ Remote cache not working → references/caching/remote-cache.md
└─ Environment causing misses → references/environment/gotchas.md
“我只想运行有更改的包”
Run only what changed?
├─ Changed packages + dependents (RECOMMENDED) → turbo run build --affected
├─ Custom base branch → --affected --affected-base=origin/develop
├─ Manual git comparison → --filter=...[origin/main]
└─ See all filter options → references/filtering/README.md
**--affected 是仅运行有更改的包的主要方式。**它会自动与默认分支进行比较,并包含依赖于这些包的其他包。
“我想筛选包”
Filter packages?
├─ Only changed packages → --affected (see above)
├─ By package name → --filter=web
├─ By directory → --filter=./apps/*
├─ Package + dependencies → --filter=web...
├─ Package + dependents → --filter=...web
└─ Complex combinations → references/filtering/patterns.md
“环境变量不起作用”
Environment issues?
├─ Vars not available at runtime → Strict mode filtering (default)
├─ Cache hits with wrong env → Var not in `env` key
├─ .env changes not causing rebuilds → .env not in `inputs`
├─ CI variables missing → references/environment/gotchas.md
└─ Framework vars (NEXT_PUBLIC_*) → Auto-included via inference
“我需要设置 CI”
CI setup?
├─ GitHub Actions → references/ci/github-actions.md
├─ Vercel deployment → references/ci/vercel.md
├─ Remote cache in CI → references/caching/remote-cache.md
├─ Only build changed packages → --affected flag
├─ Skip unnecessary builds → turbo-ignore (references/cli/commands.md)
└─ Skip container setup when no changes → turbo-ignore
“我想在开发期间监视更改”
Watch mode?
├─ Re-run tasks on change → turbo watch (references/watch/README.md)
├─ Dev servers with dependencies → Use `with` key (references/configuration/tasks.md#with)
├─ Restart dev server on dep change → Use `interruptible: true`
└─ Persistent dev tasks → Use `persistent: true`
“我需要创建/构建包结构”
Package creation/structure?
├─ Create an internal package → references/best-practices/packages.md
├─ Repository structure → references/best-practices/structure.md
├─ Dependency management → references/best-practices/dependencies.md
├─ Best practices overview → references/best-practices/README.md
├─ JIT vs Compiled packages → references/best-practices/packages.md#compilation-strategies
└─ Sharing code between apps → references/best-practices/README.md#package-types
“单体仓库应该如何组织?”
Monorepo structure?
├─ Standard layout (apps/, packages/) → references/best-practices/README.md
├─ Package types (apps vs libraries) → references/best-practices/README.md#package-types
├─ Creating internal packages → references/best-practices/packages.md
├─ TypeScript configuration → references/best-practices/structure.md#typescript-configuration
├─ ESLint configuration → references/best-practices/structure.md#eslint-configuration
├─ Dependency management → references/best-practices/dependencies.md
└─ Enforce package boundaries → references/boundaries/README.md
“我想强制执行架构边界”
Enforce boundaries?
├─ Check for violations → turbo boundaries
├─ Tag packages → references/boundaries/README.md#tags
├─ Restrict which packages can import others → references/boundaries/README.md#rule-types
└─ Prevent cross-package file imports → references/boundaries/README.md
关键反模式
在代码中使用 turbo 简写
**建议在 package.json 脚本和 CI 流水线中使用 turbo run。**简写 turbo <task> 适用于交互式终端操作。
// WRONG - using shorthand in package.json
{
"scripts": {
"build": "turbo build",
"dev": "turbo dev"
}
}
// CORRECT
{
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev"
}
}
# WRONG - using shorthand in CI
- run: turbo build --affected
# CORRECT
- run: turbo run build --affected
根目录脚本绕过 Turbo
根目录的 package.json 脚本必须调用 turbo run,而不是直接运行任务。
// WRONG - bypasses turbo entirely
{
"scripts": {
"build": "bun build",
"dev": "bun dev"
}
}
// CORRECT - delegates to turbo
{
"scripts": {
"build": "turbo run build",
"dev": "turbo run dev"
}
}
使用 && 串联 Turbo 任务
不要使用 && 串联 Turbo 任务。交由 Turbo 进行编排。
// WRONG - turbo task not using turbo run
{
"scripts": {
"changeset:publish": "bun build && changeset publish"
}
}
// CORRECT
{
"scripts": {
"changeset:publish": "turbo run build && changeset publish"
}
}
手动构建依赖项的 prebuild 脚本
像 prebuild 这样手动构建其他包的脚本会绕过 Turborepo 的依赖图。
// WRONG - manually building dependencies
{
"scripts": {
"prebuild": "cd ../../packages/types && bun run build && cd ../utils && bun run build",
"build": "next build"
}
}
不过,具体修复方式取决于是否声明了工作区依赖:
-
如果已声明依赖(例如,在
package.json中声明"@repo/types": "workspace:*"),请移除prebuild脚本。Turbo 的dependsOn: ["^build"]会自动处理。 -
如果未声明依赖,则存在
prebuild是因为没有依赖关系时不会触发^build。修复方法如下:- 将依赖添加到
package.json中:"@repo/types": "workspace:*" - 然后移除
prebuild脚本
- 将依赖添加到
// CORRECT - declare dependency, let turbo handle build order
// package.json
{
"dependencies": {
"@repo/types": "workspace:*",
"@repo/utils": "workspace:*"
},
"scripts": {
"build": "next build"
}
}
// turbo.json
{
"tasks": {
"build": {
"dependsOn": ["^build"]
}
}
}
关键要点:^build 只会在列为依赖项的包中运行构建任务。未声明依赖项 = 不会自动安排构建顺序。
范围过广的 globalDependencies
globalDependencies 会影响所有包中的所有任务。请明确指定。
// WRONG - heavy hammer, affects all hashes
{
"globalDependencies": ["**/.env.*local"]
}
// BETTER - move to task-level inputs
{
"globalDependencies": [".env"],
"tasks": {
"build": {
"inputs": ["$TURBO_DEFAULT$", ".env*"],
"outputs": ["dist/**"]
}
}
}
重复的任务配置
查找可合并的重复任务配置。Turborepo 支持共享配置模式。
// WRONG - repetitive env and inputs across tasks
{
"tasks": {
"build": {
"env": ["API_URL", "DATABASE_URL"],
"inputs": ["$TURBO_DEFAULT$", ".env*"]
},
"test": {
"env": ["API_URL", "DATABASE_URL"],
"inputs": ["$TURBO_DEFAULT$", ".env*"]
},
"dev": {
"env": ["API_URL", "DATABASE_URL"],
"inputs": ["$TURBO_DEFAULT$", ".env*"],
"cache": false,
"persistent": true
}
}
}
// BETTER - use globalEnv and globalDependencies for shared config
{
"globalEnv": ["API_URL", "DATABASE_URL"],
"globalDependencies": [".env*"],
"tasks": {
"build": {},
"test": {},
"dev": {
"cache": false,
"persistent": true
}
}
}
何时使用全局配置与任务级配置:
globalEnv/globalDependencies— 影响所有任务,用于真正共享的配置- 任务级
env/inputs— 仅在特定任务需要时使用
并非反模式:较大的 env 数组
较大的 env 数组(即使包含 50 多个变量)不是问题。这通常说明用户已仔细声明构建所依赖的环境变量。不要将其标记为问题。
使用 --parallel 标志
--parallel 标志会绕过 Turborepo 的依赖图。如果任务需要并行执行,请正确配置 dependsOn。
# WRONG - bypasses dependency graph
turbo run lint --parallel
# CORRECT - configure tasks to allow parallel execution
# In turbo.json, set dependsOn appropriately (or use transit nodes)
turbo run lint
根 turbo.json 中的特定包任务覆盖
当多个包需要不同的任务配置时,请使用包配置(每个包中的 turbo.json),而不是在根 turbo.json 中堆积 package#task 覆盖项。
// WRONG - root turbo.json with many package-specific overrides
{
"tasks": {
"test": { "dependsOn": ["build"] },
"@repo/web#test": { "outputs": ["coverage/**"] },
"@repo/api#test": { "outputs": ["coverage/**"] },
"@repo/utils#test": { "outputs": [] },
"@repo/cli#test": { "outputs": [] },
"@repo/core#test": { "outputs": [] }
}
}
// CORRECT - use Package Configurations
// Root turbo.json - base config only
{
"tasks": {
"test": { "dependsOn": ["build"] }
}
}
// packages/web/turbo.json - package-specific override
{
"extends": ["//"],
"tasks": {
"test": { "outputs": ["coverage/**"] }
}
}
// packages/api/turbo.json
{
"extends": ["//"],
"tasks": {
"test": { "outputs": ["coverage/**"] }
}
}
包配置的优势:
- 让配置贴近其影响的代码
- 保持根 turbo.json 简洁,专注于基础模式
- 更容易了解每个包有哪些特殊配置
- 可与
$TURBO_EXTENDS$配合使用,以继承并扩展数组
在根目录中使用 package#task 的情况:
- 单个包需要独特的依赖项(例如,
"deploy": { "dependsOn": ["web#build"] }) - 迁移期间的临时覆盖
详情请参阅 references/configuration/README.md#package-configurations。
在 inputs 中使用 ../ 跳出包目录
不要使用 ../ 之类的相对路径来引用包外的文件。请改用 $TURBO_ROOT$。
// WRONG - traversing out of package
{
"tasks": {
"build": {
"inputs": ["$TURBO_DEFAULT$", "../shared-config.json"]
}
}
}
// CORRECT - use $TURBO_ROOT$ for repo root
{
"tasks": {
"build": {
"inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/shared-config.json"]
}
}
}
会生成文件的任务缺少 outputs
标记缺少 outputs 之前,请先检查任务实际生成的内容:
- 阅读包的脚本(例如,
"build": "tsc"、"test": "vitest") - 确定它是否会将文件写入磁盘,还是只向 stdout 输出
- 只有当任务会生成应缓存的文件时才标记
// WRONG: build produces files but they're not cached
{
"tasks": {
"build": {
"dependsOn": ["^build"]
}
}
}
// CORRECT: build outputs are cached
{
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
}
}
}
各框架的常见输出:
- Next.js:
[".next/**", "!.next/cache/**"] - Vite/Rollup:
["dist/**"] - tsc:
["dist/**"]或自定义outDir
TypeScript 的 --noEmit 仍可能生成缓存文件:
当 tsconfig.json 中设置了 incremental: true 时,即使不生成 JS,tsc --noEmit 也会写入 .tsbuildinfo 文件。不要在检查 tsconfig 之前就假定不会生成输出:
// If tsconfig has incremental: true, tsc --noEmit produces cache files
{
"tasks": {
"typecheck": {
"outputs": ["node_modules/.cache/tsbuildinfo.json"] // or wherever tsBuildInfoFile points
}
}
}
确定 TypeScript 任务的正确输出:
- 检查 tsconfig 中是否启用了
incremental或composite - 检查
tsBuildInfoFile是否指定了自定义缓存位置(默认位置:outDir旁边或项目根目录) - 如果未启用增量模式,
tsc --noEmit不会生成文件
^build 与 build 混淆
{
"tasks": {
// ^build = run build in DEPENDENCIES first (other packages this one imports)
"build": {
"dependsOn": ["^build"]
},
// build (no ^) = run build in SAME PACKAGE first
"test": {
"dependsOn": ["build"]
},
// pkg#task = specific package's task
"deploy": {
"dependsOn": ["web#build"]
}
}
}
环境变量未纳入哈希
// WRONG: API_URL changes won't cause rebuilds
{
"tasks": {
"build": {
"outputs": ["dist/**"]
}
}
}
// CORRECT: API_URL changes invalidate cache
{
"tasks": {
"build": {
"outputs": ["dist/**"],
"env": ["API_URL", "API_KEY"]
}
}
}
.env 文件未列入 inputs
Turbo 不会加载 .env 文件,负责加载的是你的框架。但 Turbo 需要知道文件何时发生变化:
// WRONG: .env changes don't invalidate cache
{
"tasks": {
"build": {
"env": ["API_URL"]
}
}
}
// CORRECT: .env file changes invalidate cache
{
"tasks": {
"build": {
"env": ["API_URL"],
"inputs": ["$TURBO_DEFAULT$", ".env", ".env.*"]
}
}
}
Monorepo 中的根 .env 文件
将 .env 文件放在仓库根目录是一种反模式,即使对于小型 monorepo 或入门模板也是如此。这会导致包之间产生隐式耦合,也让人难以看清哪些包依赖哪些变量。
// WRONG - root .env affects all packages implicitly
my-monorepo/
├── .env # Which packages use this?
├── apps/
│ ├── web/
│ └── api/
└── packages/
// CORRECT - .env files in packages that need them
my-monorepo/
├── apps/
│ ├── web/
│ │ └── .env # Clear: web needs DATABASE_URL
│ └── api/
│ └── .env # Clear: api needs API_KEY
└── packages/
根目录 .env 文件的问题:
- 不清楚哪些包会使用哪些变量
- 所有包都会获得所有变量(即使有些变量并不需要)
- 缓存失效的粒度过粗(根目录
.env发生变化会使所有内容失效) - 存在安全风险:包可能会意外访问原本供其他包使用的敏感变量
- 坏习惯往往从小处开始,入门模板应示范正确模式
如果必须共享变量,请使用 globalEnv 明确指定共享内容,并说明原因。
严格模式下筛选 CI 变量
默认情况下,Turborepo 会将环境变量筛选为仅包含 env/globalEnv 中的变量。CI 变量可能会缺失:
// If CI scripts need GITHUB_TOKEN but it's not in env:
{
"globalPassThroughEnv": ["GITHUB_TOKEN", "CI"],
"tasks": { ... }
}
或者使用 --env-mode=loose(不建议用于生产环境)。
应放在包中的应用共享代码
// WRONG: Shared code inside an app
apps/
web/
shared/ # This breaks monorepo principles!
utils.ts
// CORRECT: Extract to a package
packages/
utils/
src/utils.ts
跨包边界访问文件
// WRONG: Reaching into another package's internals
import { Button } from "../../packages/ui/src/button";
// CORRECT: Install and import properly
import { Button } from "@repo/ui/button";
根目录依赖项过多
// WRONG: App dependencies in root
{
"dependencies": {
"react": "^18",
"next": "^14"
}
}
// CORRECT: Only repo tools in root
{
"devDependencies": {
"turbo": "latest"
}
}
常见任务配置
标准构建流水线
{
"$schema": "https://turborepo.dev/schema.v2.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**", ".next/**", "!.next/cache/**"]
},
"dev": {
"cache": false,
"persistent": true
}
}
}
如果有需要并行执行且会导致缓存失效的任务,请添加 transit 任务(见下文)。
带有 ^dev 模式的 Dev 任务(用于 turbo watch)
在根目录的 turbo.json 中,带有 dependsOn: ["^dev"] 和 persistent: false 的 dev 任务看起来可能不太寻常,但对于 turbo watch 工作流来说是正确的:
// Root turbo.json
{
"tasks": {
"dev": {
"dependsOn": ["^dev"],
"cache": false,
"persistent": false // Packages have one-shot dev scripts
}
}
}
// Package turbo.json (apps/web/turbo.json)
{
"extends": ["//"],
"tasks": {
"dev": {
"persistent": true // Apps run long-running dev servers
}
}
}
这样做为何有效:
- 软件包(例如
@acme/db、@acme/validators)使用"dev": "tsc"— 一次性类型生成任务,可快速完成 - 应用会通过
persistent: true覆盖此设置,用于实际的开发服务器(Next.js 等) turbo watch会在源文件更改时重新运行一次性软件包dev脚本,使类型保持同步
预期用法: 运行 turbo watch dev(而非 turbo run dev)。监视模式会在文件更改时重新执行一次性任务,同时让持久任务继续运行。
替代模式: 对于一次性依赖项构建,可使用单独的任务名称,例如 prepare 或 generate,以便更清楚地表达意图:
{
"tasks": {
"prepare": {
"dependsOn": ["^prepare"],
"outputs": ["dist/**"]
},
"dev": {
"dependsOn": ["prepare"],
"cache": false,
"persistent": true
}
}
}
用于支持缓存失效的并行任务的过渡节点
某些任务可以并行运行(不需要依赖项的构建产物),但依赖项的源代码更改时必须使缓存失效。
使用 dependsOn: ["^taskname"] 的问题:
- 会强制按顺序执行(速度慢)
使用 dependsOn: [](无依赖项)的问题:
- 允许并行执行(速度快)
- 但缓存不正确 — 更改依赖项的源代码不会使缓存失效
过渡节点可同时解决这两个问题:
{
"tasks": {
"transit": { "dependsOn": ["^transit"] },
"my-task": { "dependsOn": ["transit"] }
}
}
transit 任务会建立依赖关系,但不会匹配任何实际脚本,因此任务可以并行运行,同时确保缓存正确失效。
如何识别需要使用此模式的任务: 查找会读取依赖项源文件,但不需要其构建产物的任务。
使用环境变量
{
"globalEnv": ["NODE_ENV"],
"globalDependencies": [".env"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"],
"env": ["API_URL", "DATABASE_URL"]
}
}
}
参考索引
配置
| 文件 | 用途 |
|---|---|
| configuration/README.md | turbo.json 概览、软件包配置 |
| configuration/tasks.md | dependsOn、outputs、inputs、env、cache、persistent |
| configuration/global-options.md | globalEnv、globalDependencies、cacheDir、daemon、envMode |
| configuration/gotchas.md | 常见配置错误 |
缓存
| 文件 | 用途 |
|---|---|
| caching/README.md | 缓存的工作原理、哈希输入 |
| caching/remote-cache.md | Vercel 远程缓存、可自托管、登录/链接 |
| caching/gotchas.md | 调试缓存未命中、--summarize、--dry |
环境变量
| 文件 | 用途 |
|---|---|
| environment/README.md | env、globalEnv、passThroughEnv |
| environment/modes.md | Strict 与 Loose 模式、框架推断 |
| environment/gotchas.md | .env 文件、CI 问题 |
筛选
| 文件 | 用途 |
|---|---|
| filtering/README.md | --filter 语法概览 |
| filtering/patterns.md | 常见筛选模式 |
CI/CD
| 文件 | 用途 |
|---|---|
| ci/README.md | CI 通用原则 |
| ci/github-actions.md | 完整的 GitHub Actions 配置 |
| ci/vercel.md | Vercel 部署、turbo-ignore |
| ci/patterns.md | --affected、缓存策略 |
CLI
| 文件 | 用途 |
|---|---|
| cli/README.md | turbo run 基础知识 |
| cli/commands.md | turbo run 标志、turbo-ignore 和其他命令 |
最佳实践
| 文件 | 用途 |
|---|---|
| best-practices/README.md | Monorepo 最佳实践概览 |
| best-practices/structure.md | 仓库结构、工作区配置、TypeScript/ESLint 设置 |
| best-practices/packages.md | 创建内部包、JIT 与编译、导出 |
| best-practices/dependencies.md | 依赖管理、安装、版本同步 |
监视模式
| 文件 | 用途 |
|---|---|
| watch/README.md | turbo watch、可中断任务、开发工作流 |
边界(实验性)
| 文件 | 用途 |
|---|---|
| boundaries/README.md | 强制实施包隔离、基于标签的依赖规则 |
源文档
此技能基于 Turborepo 官方文档:
- 来源:Turborepo 仓库中的
docs/site/content/docs/ - 在线文档:https://turborepo.dev/docs