Category: guide
Turborepo — Monorepo Build System ที่เร็วด้วย Cache
คู่มือ Turborepo สำหรับจัดการ monorepo — task pipeline, remote caching และการตั้งค่า workspace กับ pnpm
สารบัญ
Turborepo คืออะไร
Turborepo เป็น build system สำหรับ JavaScript/TypeScript monorepo — ทำให้ build, test, lint ทำงานแบบ parallel ข้าม packages และ cache ผลลัพธ์ไว้ ถ้า code ไม่เปลี่ยน จะ skip และใช้ cache แทน
สร้าง Monorepo ใหม่
npx create-turbo@latest my-monorepo
cd my-monorepo
โครงสร้าง
my-monorepo/
├── apps/
│ ├── web/ # Astro / Next.js site
│ └── docs/ # Documentation site
├── packages/
│ ├── ui/ # Shared components
│ ├── config-ts/ # Shared tsconfig
│ └── utils/ # Shared utilities
├── turbo.json
└── package.json (root)
turbo.json — กำหนด Task Pipeline
{
"$schema": "https://turbo.build/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": [".next/**", "dist/**", ".astro/**"]
},
"test": {
"dependsOn": ["^build"],
"outputs": ["coverage/**"]
},
"lint": {
"outputs": []
},
"dev": {
"cache": false,
"persistent": true
}
}
}
"dependsOn": ["^build"] หมายถึง “รัน build ของ dependencies ก่อน” — Turborepo จัดลำดับเอง
Root package.json
{
"name": "my-monorepo",
"scripts": {
"build": "turbo build",
"dev": "turbo dev",
"test": "turbo test",
"lint": "turbo lint"
},
"devDependencies": {
"turbo": "latest"
}
}
pnpm workspace
# pnpm-workspace.yaml
packages:
- 'apps/*'
- 'packages/*'
Shared Package
// packages/utils/src/index.ts
export function formatPrice(price: number, currency = 'THB'): string {
return new Intl.NumberFormat('th-TH', {
style: 'currency', currency,
}).format(price);
}
// packages/utils/package.json
{
"name": "@repo/utils",
"exports": { ".": "./src/index.ts" }
}
// apps/web/package.json
{
"dependencies": {
"@repo/utils": "workspace:*"
}
}
Remote Cache — ใช้ cache ข้าม CI runs
npx turbo login
npx turbo link # link กับ Vercel Remote Cache (ฟรี)
หรือ self-host ด้วย ducktape / turborepo-remote-cache package
เมื่อไหร่ใช้ monorepo: มี packages ที่ share กันข้าม apps, ต้องการ atomic commits ข้าม app หลายตัว, หรือ team ต้องการ consistency ใน tooling — ถ้า project เดียวและเล็ก ไม่จำเป็น