Nâng caoKỹ thuậtclaude-code

CLAUDE.md Masterclass — Tối ưu workspace cho Claude Code

Nghe bài viết
00:00
computer monitor screengrab

CLAUDE.md là gì và tại sao nó quan trọng?

CLAUDE.md là file Markdown đặc biệt mà Claude Code đọc ngay khi khởi động. Nội dung của file này trở thành system context cho toàn bộ session — mọi quyết định Claude đưa ra đều được định hình bởi những gì bạn viết trong CLAUDE.md.

Hãy nghĩ CLAUDE.md như là bản onboarding document cho developer mới gia nhập team — ngoại trừ "developer mới" ở đây là một AI agent với khả năng đọc và ghi code. Càng viết rõ ràng, Claude càng làm việc hiệu quả hơn, ít sai hơn, và ít cần correction hơn.

Một CLAUDE.md tốt có thể tiết kiệm 30-50% tokens trong một session dài, vì Claude không phải "hỏi" hay "đoán" những thông tin cơ bản về project.

Sự khác biệt giữa project với và không có CLAUDE.md

Không có CLAUDE.md:

  • Claude phải khám phá codebase từ đầu mỗi session
  • Có thể đưa ra suggestions không phù hợp với conventions
  • Tốn nhiều tokens cho context building
  • Kết quả inconsistent giữa các session

Có CLAUDE.md tốt:

  • Claude hiểu ngay context và constraints
  • Suggestions phù hợp với team conventions ngay từ đầu
  • Tiết kiệm tokens, session nhanh hơn
  • Kết quả consistent và predictable

File Hierarchy

Claude Code đọc CLAUDE.md từ nhiều vị trí theo thứ tự ưu tiên:

1. Project root: /project/CLAUDE.md

File chính, chứa project-specific context. Nên được commit vào version control để toàn team benefit.

2. Global: ~/.claude/CLAUDE.md

Personal preferences áp dụng cho mọi project. Ví dụ: coding style cá nhân, preferred tools, shortcuts.

# ~/.claude/CLAUDE.md (personal global config)

## My Preferences
- Always use TypeScript, never plain JavaScript
- Prefer functional programming patterns
- Use descriptive variable names, avoid abbreviations
- Always add JSDoc for public functions

## My Common Tools
- Package manager: pnpm (not npm or yarn)
- Test framework: Vitest
- Linter: ESLint + Prettier

3. Subdirectory: /project/.claude/CLAUDE.md

Context cho một phần cụ thể của project. Hữu ích cho monorepos.

/project/
├── CLAUDE.md              # Root project context
├── .claude/
│   ├── CLAUDE.md          # Advanced overrides
│   ├── settings.json      # Tool permissions
│   └── hooks/             # Automation hooks
├── packages/
│   ├── frontend/
│   │   └── CLAUDE.md      # Frontend-specific context
│   └── backend/
│       └── CLAUDE.md      # Backend-specific context

Claude merge tất cả các file CLAUDE.md theo thứ tự ưu tiên, với subdirectory CLAUDE.md override parent khi có conflict.

Cấu trúc CLAUDE.md chuẩn

Sau đây là template structure được khuyến nghị:

# CLAUDE.md

## Role
[Mô tả Claude nên đóng vai trò gì trong project này]

## Project Overview
[Project này làm gì, cho ai, tại sao nó tồn tại]

## Tech Stack
[Liệt kê tất cả technologies, versions quan trọng]

## Project Structure
[Giải thích cấu trúc thư mục quan trọng]

## Development Commands
[Các lệnh thường dùng nhất]

## Coding Conventions
[Rules về code style, patterns, naming]

## Architecture Decisions
[Các quyết định kiến trúc quan trọng và lý do]

## Do NOT
[Những điều tuyệt đối không được làm]

## Workflows
[Các workflow cụ thể của team]

Các Section cần thiết

Role Section

Đây là section nhiều người bỏ qua nhưng lại rất có impact. Cho Claude biết nó đang đóng vai trò gì:

## Role
Bạn là senior backend engineer trong team này. Ưu tiên:
1. Code correctness và reliability hơn tốc độ viết
2. Security — luôn validate input, sanitize output
3. Performance — cân nhắc database indexes và query optimization
4. Maintainability — code phải dễ đọc và dễ test

Tech Stack Section

Liệt kê cụ thể, bao gồm versions quan trọng:

## Tech Stack
- Runtime: Node.js 20 LTS
- Framework: Fastify 4 (NOT Express)
- Database: PostgreSQL 15 + Prisma 5 ORM
- Cache: Redis 7
- Testing: Vitest + Supertest
- Language: TypeScript 5.3 (strict: true)
- Deployment: Docker + Kubernetes on GCP

Lưu ý: ghi rõ "NOT Express" nếu bạn dùng Fastify. Sự phân biệt tường minh giúp Claude không nhầm lẫn framework.

Project Structure Section

## Project Structure
src/
├── api/         # Route handlers only, NO business logic
├── services/    # Business logic layer
├── repositories/ # Database access layer (Prisma queries)
├── models/      # TypeScript interfaces and types
├── middleware/  # Fastify middleware
├── utils/       # Pure utility functions
└── config/      # Configuration management

IMPORTANT: Follow this layered architecture strictly.
Services call Repositories. Routes call Services. Never skip layers.

Development Commands

## Commands
- Dev server: `npm run dev`
- Run tests: `npm test`
- Watch tests: `npm run test:watch`
- Type check: `npm run typecheck`
- Lint: `npm run lint`
- DB migrate: `npx prisma migrate dev --name [description]`
- DB studio: `npx prisma studio`
- Docker up: `docker compose up -d`
- Generate API docs: `npm run docs:generate`

Claude Code sẽ tự động chạy các commands này khi cần verify, mà không cần bạn nhắc nhở.

Coding Conventions

## Conventions

### Naming
- Variables/functions: camelCase
- Classes/interfaces: PascalCase
- Constants: SCREAMING_SNAKE_CASE
- Database tables: snake_case
- Files: kebab-case.ts

### Error Handling
- Use custom error classes extending AppError
- Always include error code and message
- Log errors with context before throwing
- Never swallow errors silently

### Async
- Always use async/await, never .then().catch()
- Wrap top-level async in try/catch
- Use Promise.all() for parallel operations

### Testing
- Unit tests for all service methods
- Integration tests for all API endpoints
- Use factories (not fixtures) for test data
- Mock external services, never make real API calls in tests

Do NOT Section

Đây là section quan trọng nhất để prevent mistakes:

## Do NOT
- NEVER use `any` type in TypeScript — use `unknown` + type guards
- NEVER commit environment variables or secrets
- NEVER write raw SQL queries — use Prisma
- NEVER modify database migrations after they've been committed
- NEVER skip input validation in API handlers
- NEVER use synchronous file operations (fs.readFileSync) in request handlers
- NEVER delete or modify /prisma/migrations/
- NEVER push directly to main branch

Ví dụ từ production projects

Full-stack SaaS application

# CLAUDE.md — TaskFlow SaaS

## Overview
B2B task management SaaS. Multi-tenant architecture.
Each customer (Organization) has isolated data.

## Critical: Multi-tenancy
EVERY database query MUST include organizationId filter.
This is the most important security requirement.

```typescript
// CORRECT
const tasks = await prisma.task.findMany({
  where: { organizationId: ctx.organizationId, ...filters }
});

// WRONG — data leak risk!
const tasks = await prisma.task.findMany({ where: filters });
```

## Stack
- Next.js 14 (App Router) + TypeScript
- Prisma + PostgreSQL (Supabase)
- Stripe for billing
- Resend for emails
- Vercel deployment

## Key Paths
- /app/(dashboard)/ — authenticated app routes
- /app/(marketing)/ — public marketing pages
- /app/api/ — API route handlers
- /lib/ — shared utilities and configs

## Auth
Using NextAuth v5. Session always includes organizationId.
Access via: `const session = await auth()`

Microservices backend

# CLAUDE.md — Payment Service

## This Service
Handles all payment processing for the platform.
Part of larger microservices architecture.

## Boundaries — IMPORTANT
This service ONLY:
- Processes payments via Stripe
- Stores transaction records
- Emits payment events to message queue

This service does NOT:
- Know about users (get user data via event or API)
- Send emails (emit event, let notification service handle)
- Update order status (emit event, let order service handle)

## Event Schema
Events published to RabbitMQ exchange "payments":
- payment.succeeded — { transactionId, orderId, amount, currency }
- payment.failed — { orderId, reason, retryable }
- payment.refunded — { transactionId, refundId, amount }

## Stripe Integration
Using Stripe SDK v14. Webhook endpoint: /webhooks/stripe
Signature verification is REQUIRED for all webhooks.

Common Patterns

Monorepo Pattern

Với monorepo sử dụng Turborepo hoặc Nx:

# Root CLAUDE.md
## Monorepo Structure
This is a Turborepo monorepo.

Apps: packages/apps/
- web — Next.js frontend
- api — Fastify backend
- admin — Admin dashboard

Packages: packages/libs/
- ui — Shared component library
- types — Shared TypeScript types
- utils — Shared utilities
- config — Shared configs (ESLint, TypeScript)

## Rules
- Shared types go in packages/libs/types, NOT in individual apps
- UI components go in packages/libs/ui if used by 2+ apps
- Each app has its own CLAUDE.md with app-specific context

Frontend-only Project

# CLAUDE.md — Marketing Website

## Project
Static marketing site with Next.js + Contentful CMS.

## Important: Static Generation
ALL pages must use static generation (generateStaticParams).
NO server-side rendering, NO dynamic routes without static params.
Site deployed on Cloudflare Pages — no Node.js runtime.

## Content
Blog posts and case studies come from Contentful.
Never hardcode content that should be in Contentful.

## Performance Budget
- Core Web Vitals: LCP < 2.5s, FID < 100ms, CLS < 0.1
- Bundle size: < 100KB for initial JS
- Always check bundle impact before adding new dependencies

Advanced: Custom Commands

Định nghĩa custom slash commands trong .claude/commands/:

# .claude/commands/deploy-staging.md
Deploy to staging environment:
1. Run `npm run build` and ensure it passes
2. Run `npm test` and ensure all tests pass
3. Run `npm run typecheck`
4. Create a git tag with format staging-YYYY-MM-DD-HH
5. Push tag to trigger CI/CD pipeline
6. Confirm deployment URL: staging.myapp.com

Gọi bằng: /deploy-staging

Advanced: Memory System

Claude Code có thể ghi nhớ thông tin quan trọng giữa các sessions qua memory files:

.claude/
├── memory/
│   ├── architecture-decisions.md
│   ├── known-issues.md
│   └── sprint-context.md

Reference trong CLAUDE.md:

## Memory
- Read .claude/memory/architecture-decisions.md for important ADRs
- Read .claude/memory/known-issues.md for current known bugs
- Update .claude/memory/sprint-context.md when sprint goals change

Advanced: Skill References

Encode reusable workflows như skills:

.claude/skills/
├── create-feature.md      # Standard feature development workflow
├── hotfix.md              # Emergency hotfix process
└── db-migration.md        # Database migration checklist
# .claude/skills/create-feature.md
## New Feature Workflow
1. Create branch: git checkout -b feature/[name]
2. Update/create relevant TypeScript interfaces in /models/
3. Write failing tests first (TDD)
4. Implement feature
5. Ensure all tests pass
6. Run typecheck
7. Update API documentation if new endpoints
8. Create PR with description following template in .github/pull_request_template.md

Anti-patterns cần tránh

1. CLAUDE.md quá ngắn

Sai:

## Stack
Next.js, TypeScript, Prisma

Đúng: Bao gồm versions, important patterns, structure, và commands đầy đủ.

2. CLAUDE.md không cập nhật

CLAUDE.md phải được cập nhật khi tech stack thay đổi, conventions thay đổi, hoặc có new architectural decisions. Một CLAUDE.md lỗi thời còn tệ hơn không có.

3. Viết quá chung chung

Sai: "Follow best practices"

Đúng: "Use Repository pattern for all database access. Never put Prisma calls directly in route handlers."

4. Thiếu "Do NOT" section

Những điều không được làm thường quan trọng hơn những điều nên làm. Security issues, architectural violations thường đến từ những điều không được ghi rõ là "forbidden".

5. Không giải thích lý do

Claude (và developer mới) cần hiểu tại sao, không chỉ cái gì:

## Why We Use X
- Using Fastify instead of Express: 3x better performance,
  native schema validation, TypeScript-first design
- Using Prisma instead of raw SQL: type-safe queries,
  auto-generated migrations, easy schema evolution

Checklist: CLAUDE.md hoàn chỉnh

  • Role và responsibility của Claude trong project
  • Project overview (mục đích, user, tech)
  • Full tech stack với versions
  • Cấu trúc thư mục với giải thích
  • Tất cả development commands
  • Coding conventions (naming, patterns, style)
  • Architecture decisions và lý do
  • Security requirements
  • Testing requirements
  • Explicit "Do NOT" list
  • Team-specific workflows
  • Links đến relevant docs nếu có

Kết luận

CLAUDE.md không phải là boilerplate bạn copy-paste rồi để đó — đây là living document cần được maintain như code. Đầu tư 30 phút viết CLAUDE.md tốt cho project mới sẽ tiết kiệm hàng giờ frustration và corrections về sau.

Nguyên tắc cuối cùng: viết CLAUDE.md như là bạn đang onboard một senior developer mới cực kỳ thông minh nhưng chưa biết gì về project của bạn. Cung cấp đủ context để họ (và Claude) có thể làm việc hiệu quả ngay từ ngày đầu tiên.


Bài viết liên quan

Tính năng liên quan:CLAUDE.mdClaude CodeProjects

Bai viet co huu ich khong?

Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.

Bình luận (3)
Ảnh đại diện
Đăng nhập để bình luận...
Đăng nhập để bình luận
  • Đang tải bình luận...

Đăng ký nhận bản tin

Nhận bài viết hay nhất về sản phẩm và vận hành, gửi thẳng vào hộp thư của bạn.

Bảo mật thông tin. Hủy đăng ký bất cứ lúc nào. Chính sách bảo mật.