25 tháng 1, 2026 · 11 phút đọc
Monorepo hiện đại với Turborepo: chia sẻ code giữa apps
Cấu hình Turborepo cho workspace với multiple Next.js apps, shared packages và CI caching hiệu quả.
Monorepo cho phép chia sẻ code giữa nhiều apps và packages trong một repository. Turborepo là build system layer trên npm/pnpm/yarn workspaces, giải quyết vấn đề build order và caching mà workspaces đơn thuần không có.
Workspace Structure
Cấu trúc phổ biến: apps/ cho applications (web, mobile, admin), packages/ cho shared code (ui, utils, config, database). Mỗi package có package.json riêng với exports field để định nghĩa public API. TypeScript project references cho type-checking cross-package.
Đặt tên packages với scope: @acme/ui, @acme/utils. Dùng workspace: protocol trong package.json dependencies để reference local packages. pnpm workspace.yaml define workspace members.
turbo.json Configuration
turbo.json định nghĩa pipeline: dependency ordering (^build nghĩa là build dependencies first), inputs (files ảnh hưởng đến output), outputs (artifacts được cache). Turborepo chỉ re-run tasks khi inputs thay đổi.
Remote Caching
Remote cache cho phép chia sẻ build artifacts giữa team members và CI. Vercel cung cấp remote cache miễn phí cho Turborepo. Kết quả: CI pull cache từ team member đã build trước, skip toàn bộ build step. Tiết kiệm hàng giờ CI time.
Shared UI Package
Packages/ui là nơi đặt design system components dùng chung. Export components từ index.ts và define trong package.json exports. Với Next.js, dùng transpilePackages hoặc export client/server components rõ ràng để tránh 'use client' boundary issues.