
使用 Turborepo 的 Monorepo 架构:扩展前端项目
Turborepo 通过智能缓存和并行执行使 monorepo 变得快速。
项目设置
npx create-turbo@latest my-monorepo
cd my-monorepo
my-monorepo/
├── apps/
│ ├── web/ # Next.js 应用
│ ├── admin/ # 管理后台
│ └── api/ # NestJS API
├── packages/
│ ├── ui/ # 共享组件库
│ ├── utils/ # 共享工具函数
│ ├── config/ # 共享配置(ESLint、TypeScript)
│ └── types/ # 共享 TypeScript 类型
├── turbo.json
└── package.json

turbo.json 配置
{
"$schema": "https://turborepo.com/schema.json",
"pipeline": {
"build": {
"dependsOn": ["^build"],
"outputs": [".next/**", "dist/**"],
"cache": true
},
"test": {
"dependsOn": ["build"],
"outputs": ["coverage/**"],
"cache": true
},
"lint": {
"outputs": [],
"cache": true
},
"dev": {
"cache": false,
"persistent": true
},
"typecheck": {
"dependsOn": ["^build"],
"cache": true
}
}
}

共享 UI 包
// packages/ui/src/Button.tsx
import * as React from 'react';
export interface ButtonProps {
variant?: 'primary' | 'secondary';
size?: 'sm' | 'md' | 'lg';
children: React.ReactNode;
onClick?: () => void;
}
export const Button: React.FC<ButtonProps> = ({
variant = 'primary',
size = 'md',
children,
onClick
}) => (
<button
className={`btn btn-${variant} btn-${size}`}
onClick={onClick}
>
{children}
</button>
);
// packages/ui/package.json
{
"name": "@myrepo/ui",
"exports": {
".": "./src/index.ts"
},
"devDependencies": {
"typescript": "^5.0.0",
"@myrepo/config": "*"
}
}

共享 TypeScript 配置
// packages/config/tsconfig/base.json
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"skipLibCheck": true,
"noEmit": true
}
}
// packages/config/tsconfig/react.json
{
"extends": "./base.json",
"compilerOptions": {
"jsx": "react-jsx",
"lib": ["ES2022", "DOM"]
}
}
远程缓存
# 登录到 Vercel 远程缓存
npx turbo login
# 链接到 Vercel
npx turbo link
# CI 配置
# turbo.json 自动使用远程缓存
TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}
TURBO_TEAM=${{ secrets.TURBO_TEAM }}
运行任务
# 构建所有内容
turbo build
# 构建特定应用及其依赖
turbo build --filter=web
# 仅构建已更改的包
turbo build --filter="[main]"
# 并行运行测试
turbo test
# 为所有应用运行开发模式
turbo dev
Turborepo 的缓存可以将大型 monorepo 的 CI 构建时间减少 70-80%。