跳至主要內容
精選 Configuration Best Practices CLAUDE.md Memory

CLAUDE.md 設計原則:打造你的專案憲法

掌握 7 個設計原則,讓你的 Claude Code 專案脫穎而出。CLAUDE.md 是有效 AI 協作的基石。

2026年1月10日 15 分鐘閱讀 作者:ClaudeWorld

你的 CLAUDE.md 是任何 Claude Code 專案中最重要的檔案。它不只是設定檔——它是一部憲法,定義了 Claude 如何理解並與你的程式碼庫協作。

一個精心設計的 CLAUDE.md 能將 Claude 從通用助手轉變為專業團隊成員,了解你的標準、尊重你的約束,並產出一致的結果。

本指南涵蓋官方記憶系統,以及區分優秀 CLAUDE.md 與普通 CLAUDE.md 的 7 個原則。

理解 Claude Code 的記憶系統

四層記憶階層

根據 官方 Claude Code 文件,Claude Code 使用四層記憶階層,更具體的層級會覆蓋更通用的層級:

┌─────────────────────────────────────────────────┐
│  Layer 1: Enterprise/Organization               │
│  Location: /etc/claude-code/settings.json       │
│  Scope: All users in organization               │
│  Control: IT department                         │
│  Purpose: Security policies, MCP allowlists     │
├─────────────────────────────────────────────────┤
│  Layer 2: User Global                           │
│  Location: ~/.claude/CLAUDE.md                  │
│           ~/.claude/settings.json               │
│  Scope: All your projects                       │
│  Purpose: Personal preferences, global tools    │
├─────────────────────────────────────────────────┤
│  Layer 3: Project                               │
│  Location: ./CLAUDE.md or ./.claude/CLAUDE.md   │
│           ./.claude/settings.json               │
│  Scope: Team-shared, version controlled         │
│  Purpose: Project standards, conventions        │
├─────────────────────────────────────────────────┤
│  Layer 4: Project Local                         │
│  Location: ./CLAUDE.local.md                    │
│  Scope: Personal only (gitignored)              │
│  Purpose: Individual overrides                  │
└─────────────────────────────────────────────────┘

優先順序: Project Local > Project > User Global > Enterprise

各層級控制內容

層級CLAUDE.mdsettings.json用途
Enterprise組織政策MCP 白名單、工具限制合規性
User Global個人風格全域 MCP、外掛偏好設定
Project團隊標準專案 MCP、權限一致性
Project Local個人覆寫本地測試彈性

設定檔說明

CLAUDE.md - Claude 在 session 開始時讀取的自然語言指示:

# Project Constitution
- All code must have tests
- Use TypeScript strict mode
- Follow existing patterns

settings.json - 工具和權限的結構化設定:

{
  "permissions": {
    "allow": ["Read", "Write", "Edit", "Bash(npm:*)"],
    "deny": ["Read(.env)"]
  },
  "enableAllProjectMcpServers": true,
  "ignorePatterns": ["node_modules/**", ".git/**"]
}

使用路徑特定設定的模組化規則

對於複雜專案,使用 .claude/rules/ 目錄(v2.0.20+):

your-project/
├── .claude/
│   ├── CLAUDE.md           # Main constitution
│   ├── settings.json       # Permissions, MCP
│   └── rules/
│       ├── code-style.md   # Coding standards
│       ├── testing.md      # Test requirements
│       ├── security.md     # Security policies
│       └── api.md          # API conventions

規則可以使用 frontmatter 設定為路徑特定

---
paths: src/api/**/*.ts
---

# API Development Rules
- All endpoints must validate inputs using Zod
- Use standardized error responses from src/lib/errors.ts
- Include OpenAPI documentation comments

這表示規則僅在 Claude 處理符合 src/api/**/*.ts 的檔案時才會套用。

7 個設計原則

原則 1:清晰優於巧妙

撰寫清晰、明確的指示。Claude 應該立即理解你的意圖,無需額外詮釋。

不要這樣做:

# Code should be good
Write clean code. Follow best practices.

改成這樣:

# Code Standards
- Use TypeScript strict mode (no `any` types)
- Functions must have explicit return types
- Maximum function length: 50 lines
- Maximum file length: 300 lines
- Use early returns to reduce nesting

為什麼重要: 模糊的指示導致不一致的結果。「好程式碼」對不同人有不同含義。具體標準能產出可重現的結果。

原則 2:權威階層

從通用到具體分層設定。每一層都應有明確的目的。

結構:

# CLAUDE.md

## Non-Negotiables (Cannot be overridden)
- All PRs require tests
- No credentials in code
- Security review for auth changes

## Project Defaults (Can be overridden per-task)
- Prefer functional programming style
- Use named exports over default exports
- Write documentation for public APIs

## Preferences (Suggestions, not requirements)
- Consider performance implications
- Prefer composition over inheritance

為什麼重要: 並非所有規則都同等重要。有些是絕對的(安全性),有些是指引(風格)。明確說明可防止 Claude 違反關鍵規則,同時在適當的地方保持彈性。

原則 3:許可而非限制

定義 Claude 可以做什麼,而不是它不能做什麼。啟用高效工作,而不是不斷阻擋。

不要這樣做:

# Restrictions
- Don't modify production files
- Don't run destructive commands
- Don't commit without asking
- Don't install packages without approval

改成這樣:

# Autonomous Operations (No confirmation needed)
- Read any file in the project
- Run tests and linting
- Create/modify files in src/ and tests/
- Install devDependencies
- Create local branches

# Requires Confirmation
- Modifying .env or config files
- Installing production dependencies
- Pushing to remote branches
- Deleting files

為什麼重要: 限制性的 CLAUDE.md 會造成阻力。Claude 不斷詢問許可,打斷你的工作流程。具有明確界限的許可性 CLAUDE.md 能啟用自主工作,同時保護重要事項。

settings.json 權限語法

來自官方文件

{
  "permissions": {
    "allow": [
      "Read",
      "Write",
      "Edit",
      "Bash(npm run:*)",
      "Bash(git:*)"
    ],
    "deny": [
      "Read(.env)",
      "Read(secrets/**)"
    ]
  }
}

模式語法:

  • Bash(npm run:*) - 允許所有 npm run 指令
  • Bash(git:*) - 允許所有 git 指令
  • Read(.env) - 拒絕讀取 .env 檔案
  • Read(secrets/**) - 拒絕讀取 secrets/ 中的任何內容

原則 4:上下文為王

預先提供相關上下文。Claude 知道得越多,表現越好。

必要的上下文:

# Project Overview
A Next.js 14 e-commerce platform with:
- App Router architecture
- Prisma + PostgreSQL database
- Stripe for payments
- Resend for emails

# Directory Structure
src/
├── app/           # Next.js App Router pages
├── components/    # Shared React components
├── lib/           # Utility functions and configs
├── services/      # Business logic
└── types/         # TypeScript type definitions

# Key Files
- src/lib/db.ts - Database client (Prisma)
- src/lib/auth.ts - Authentication utilities (NextAuth)
- src/services/ - Domain-specific logic

# Commands
- npm run dev - Start development server (port 3000)
- npm test - Run tests (Vitest)
- npm run lint - Check code quality (ESLint)
- npm run build - Production build

引入其他檔案以獲取詳細資訊:

See @README.md for project overview.
See @docs/architecture.md for system design.
See @package.json for available scripts.

為什麼重要: 上下文消除猜測。當 Claude 知道你的技術棧、檔案結構和慣例時,它會產出自然融入你專案的程式碼。

原則 5:可執行的標準

每個指引都應該是可執行的。如果 Claude 無法直接套用,就沒有用處。

不可執行:

- Write type-safe code
- Follow security best practices
- Make it performant

可執行:

# Type Safety
- Enable TypeScript strict mode in tsconfig.json
- Never use `any` - use `unknown` and narrow with type guards
- Define interfaces for all API responses in src/types/

# Security
- Validate all user inputs using Zod schemas
- Sanitize data before database queries
- Use parameterized queries exclusively (Prisma handles this)
- Never log sensitive data (passwords, tokens, PII)

# Performance
- Lazy load components over 50KB using next/dynamic
- Use React.memo for components with expensive renders
- Add database indexes for queries taking >100ms
- Use React Server Components for data fetching

為什麼重要: 沒有具體內容的「最佳實踐」是沒有意義的。可執行的標準可直接轉化為 Claude 可以做出的程式碼決策。

原則 6:逃生口

定義何時可以打破規則。僵化的規則造成挫折;有明確例外的彈性規則能實現務實。

# Testing Requirements
All features must have tests.

**Exceptions:**
- Prototypes and experiments (prefix with `_experimental`)
- One-time scripts in `scripts/`
- When explicitly told to skip tests

# Documentation Requirements
Public APIs must have JSDoc comments.

**Exceptions:**
- Internal utilities with obvious names
- Generated code
- Test files

為什麼重要: 真實世界的開發需要彈性。沒有逃生口,你會發現自己不斷覆寫自己的規則。明確的例外比隱性的規則違反更好。

原則 7:活文件

你的 CLAUDE.md 隨專案演進。版本控制它、定期檢視它,並根據有效的方式更新它。

# CLAUDE.md

Last updated: 2026-01-10
Version: 2.3

## Changelog
- 2.3: Added API error handling standards
- 2.2: Updated test coverage requirements (80% → 85%)
- 2.1: Added security review requirements for payment code
- 2.0: Major restructure for clarity

## Feedback
If these guidelines cause friction, document the issue
in `.claude/feedback.md` for review.

檢視觸發時機:

  • 完成重大功能後
  • 當 Claude 持續誤解某些事情時
  • 當團隊成員加入或離開時
  • 當技術棧變更時

Agent 委派規則

定義 Claude 何時應委派給專門的 agents:

## Agent Delegation

### Automatic Triggers
- Files in auth/, payment/, admin/ → security-auditor
- New API endpoints → code-reviewer
- Performance-sensitive code → benchmark first

### Manual Triggers
- Complex refactoring → Parallel Explore agents
- Full codebase review → Multi-agent analysis
- Architecture decisions → Plan agent

### Agent Configuration
code-reviewer:
  - Check for OWASP Top 10 vulnerabilities
  - Verify error handling patterns
  - Ensure consistent code style

security-auditor:
  - Scan for hardcoded secrets
  - Check authentication flows
  - Verify input validation

Knowledge Graph Memory(MCP)

Claude Code 透過 Memory MCP 支援持久化記憶:

# Add Memory MCP with project isolation
claude mcp add --scope project memory \
  -e MEMORY_FILE_PATH=./.claude/memory.json \
  -- npx -y @modelcontextprotocol/server-memory

重要: 務必使用 MEMORY_FILE_PATH 進行專案隔離。否則,所有專案會共用同一個記憶。

Memory 指令:

  • /memory-save - 儲存重要決策
  • /memory-search - 尋找已儲存的知識
  • /memory-list - 列出所有實體
  • /memory-audit - 檢查記憶健康狀態

實用範本

這是一個結合所有原則的完整 CLAUDE.md 範本:

# Project Constitution

## Project Overview
[One paragraph describing what this project does]

## Tech Stack
- Framework: [e.g., Next.js 14, App Router]
- Language: [e.g., TypeScript 5.x, strict mode]
- Database: [e.g., PostgreSQL via Prisma]
- Testing: [e.g., Vitest + React Testing Library]

## Directory Structure
src/
├── app/           # [Purpose]
├── components/    # [Purpose]
├── lib/           # [Purpose]
└── services/      # [Purpose]

## Commands
- `npm run dev` - Start development
- `npm test` - Run tests
- `npm run lint` - Check code quality

## Code Standards

### TypeScript
- Strict mode enabled
- No `any` types (use `unknown`)
- Explicit return types on functions

### React
- Functional components only
- Use React Server Components by default
- Client components must be explicitly marked

### Testing
- All features require tests
- Minimum 80% coverage for new code
- Integration tests for API routes

## Autonomous Operations
Claude may freely:
- Read all project files
- Create/modify files in src/ and tests/
- Run tests and linting
- Create local git branches

## Requires Confirmation
- Installing production dependencies
- Modifying environment variables
- Pushing to remote
- Deleting files

## Agent Delegation
- Complex refactoring → Parallel Explore agents
- Security-sensitive changes → security-auditor
- API changes → code-reviewer

## Non-Negotiables
- All code must have tests
- No secrets in code
- Security review for auth/payment code

常見錯誤

錯誤 1:太長

500 行的 CLAUDE.md 違背了目的。保持可快速掃描。

修正: 將詳細指南提取到 .claude/rules/ 並引入它們。

錯誤 2:太模糊

「寫好程式碼」不是可執行的。

修正: 將每個指引轉換為具體、可檢查的要求。

錯誤 3:太限制

每件事都要求確認會造成阻力。

修正: 識別真正有風險的事項,其餘都允許。

錯誤 4:從不更新

過時的 CLAUDE.md 造成混淆。

修正: 設定每月檢視提醒。在重大功能後更新。

錯誤 5:複製貼上

使用別人的 CLAUDE.md 而不調整。

修正: 從範本開始,但根據你專案的特定需求客製化。

錯誤 6:忽略層級階層

把所有東西都放在專案 CLAUDE.md 中,而不是使用適當的層級。

修正: 個人偏好放在 ~/.claude/CLAUDE.md,專案標準放在專案 CLAUDE.md,個人微調放在 CLAUDE.local.md

開始使用

今天:

  1. 在你的專案中執行 /init 建立基本 CLAUDE.md
  2. 新增你的專案概述和技術棧
  3. 定義 3-5 個不可協商的規則

這週:

  1. 新增目錄結構和關鍵檔案
  2. 定義自主操作 vs 需要確認
  3. 新增你最重要的程式碼標準

這個月:

  1. 根據實際使用情況精進
  2. 新增 agent 委派規則
  3. 將詳細指南提取到 .claude/rules/ 目錄
  4. 設定 Memory MCP 以獲得持久化知識

衡量成功

你的 CLAUDE.md 有效時:

  • Claude 第一次就產出符合你風格的程式碼
  • 你很少需要糾正同樣的錯誤兩次
  • 新團隊成員可以更快上手
  • 程式碼審查中的風格評論更少

你的 CLAUDE.md 需要改進時:

  • Claude 持續詢問澄清問題
  • 你不斷糾正相同的模式
  • session 之間的輸出不一致
  • 你發現自己在提示中重複上下文

最好的 CLAUDE.md 檔案不是一天寫成的——它們透過使用而演進。從簡單開始,觀察什麼有效,然後迭代。

來源:Claude Code 文件Claude Code GitHubMemory MCP