cropped 房地產阿宥(AI房仲).png

CLAUDE.md 設定完整教學|Karpathy 開源方法讓 Claude Code 記住你的習慣(2026最新)

CLAUDE.md 設定教學能讓你的 Claude Code 記住專案習慣、coding style、常用指令,不必每次對話都重複說明。2026 年 4 月 17 日,Andrej Karpathy 開源的 CLAUDE.md 設定方法在 GitHub 今日獲得 +7,959 星,證明這套方法能有效降低 AI 溝通成本。本文將完整拆解 Claude Code CLAUDE.md 設定 的每個步驟、提供 10 個實戰範例、說明 CLAUDE.md 怎麼寫 才能讓 AI 真正理解你的需求,並整合 Karpathy 強調的「把 AI 當 junior dev」核心思維,讓你的專案協作效率提升 3 倍以上。

什麼是 CLAUDE.md?為什麼需要它?

CLAUDE.md 是一個純文字設定檔案,放在專案根目錄(或全域位置 ~/.claude/CLAUDE.md),每次你在 Claude Code 開啟該專案時,Claude 會自動讀取這個檔案,把裡面的指示當作「專案記憶」。

想像這個場景:你正在開發一個 Python 專案,你希望 Claude Code 每次寫程式時:

  • 使用 python3 而非 python
  • 所有檔案加上 # -*- coding: utf-8 -*-
  • 禁止使用 os.system(),改用 subprocess
  • 測試檔案必須放在 tests/ 資料夾

如果沒有 CLAUDE.md,你每次新對話都要重複說這些規則。有了 CLAUDE.md,你只寫一次,Claude 每次都記得。

💡 CLAUDE.md 不是 AI 訓練資料,而是「每次對話的前置提示詞」,類似給助理的 SOP 手冊。

Claude Code 專案設定的核心就是透過 CLAUDE.md 建立一致的協作規範,讓 AI 不再需要猜測你的偏好。

為什麼 Karpathy 的方法值得學?GitHub +7,959 星的背書

Andrej Karpathy(前 Tesla AI 總監、OpenAI 創始成員)在 2026 年 4 月公開他使用 Claude Code 的方法論,核心思維是:

「把 AI 當成 junior developer,給它清楚的 context、明確的禁止行為、可查證的範例,它就能穩定輸出符合專案規範的程式碼。」

他的 CLAUDE.md 設定方法強調三個原則:

  1. 不要讓 AI 猜測:明確寫出偏好,而非假設 AI 會「自動理解」
  2. 禁止行為清單:列出「不可以做的事」比列出「可以做的事」更有效
  3. 提供實際範例:一個程式碼範例勝過三段文字說明

這套方法在他的 LLM101n 課程專案中實際驗證,Karpathy Claude Code 技巧讓他的 AI 協作效率提升到「幾乎不需要修改 AI 生成的程式碼」的程度。

💡 GitHub 今日 +7,959 星的熱度顯示,這套方法已被全球開發者驗證有效,不是理論,而是實戰經驗。

CLAUDE.md 完整設定步驟(5 分鐘上手)

以下是從零開始建立 CLAUDE.md 的標準流程,適用於任何程式語言專案:

步驟一:決定 CLAUDE.md 放置位置

CLAUDE.md 可以放在兩個地方,依需求選擇:

位置適用場景優先權
~/.claude/CLAUDE.md全域設定,所有專案共用(如個人 coding style、常用工具偏好)低(專案設定會覆蓋)
/your-project/CLAUDE.md專案專屬設定(如專案架構、API 規範、團隊約定)高(會覆蓋全域設定)

建議做法:

  • 先建立全域 ~/.claude/CLAUDE.md,寫入你的通用偏好(如語言、編輯器、禁止行為)
  • 每個專案再建立專案層級的 CLAUDE.md,補充專案特定規則
# macOS / Linux
mkdir -p ~/.claude
touch ~/.claude/CLAUDE.md

# 專案層級
cd /path/to/your-project
touch CLAUDE.md

步驟二:定義專案角色與目標

CLAUDE.md 的第一段應該清楚說明「這個專案在做什麼」、「Claude 扮演什麼角色」。Karpathy 強調:給 AI 清楚的角色定位,它才知道該用什麼標準判斷

# My Python Data Pipeline Project

You are a Python developer assistant helping build a data pipeline.
Project goal: ETL system processing 1M+ records/day from APIs to PostgreSQL.

Your role:
- Write production-ready Python 3.11+ code
- Follow PEP 8 style guide
- Prioritize performance and error handling
- Suggest optimizations when you see bottlenecks

步驟三:列出技術棧與工具偏好

明確告訴 Claude 專案使用什麼技術、哪些工具是首選:

## Tech Stack
- Python 3.11+ (always use `python3` command, not `python`)
- PostgreSQL 15
- Poetry for dependency management
- pytest for testing
- Black for formatting (line length: 100)
- mypy for type checking

## Preferred Libraries
- Use `requests` for HTTP, not `urllib`
- Use `pandas` for data manipulation
- Use `sqlalchemy` for database operations
- Use `loguru` for logging, not built-in `logging`

步驟四:定義禁止行為(最關鍵)

Karpathy 方法的核心:明確列出「不可以做的事」。這比「可以做的事」更有約束力。

## ❌ Prohibited Behaviors
- DO NOT use `os.system()` or `subprocess.call()` without error handling
- DO NOT commit code without type hints
- DO NOT use `print()` for logging (use loguru instead)
- DO NOT store secrets in code (read from environment variables)
- DO NOT create files outside the project directory
- DO NOT use mutable default arguments in functions

💡 用「DO NOT」開頭的禁止清單,比「應該做」的指示更能防止 AI 犯錯。

步驟五:提供程式碼範例模板

給一個「標準程式碼範例」,讓 Claude 知道你期望的風格:

## Code Example Template
```python
# -*- coding: utf-8 -*-
"""
Module description here.
"""
from typing import List, Optional
from loguru import logger

def process_data(
    input_path: str,
    output_path: str,
    batch_size: int = 1000
) -> List[dict]:
    """
    Process data from input file to output file.
    
    Args:
        input_path: Path to input CSV file
        output_path: Path to output JSON file
        batch_size: Number of records per batch
        
    Returns:
        List of processed records
        
    Raises:
        FileNotFoundError: If input file doesn't exist
    """
    logger.info(f"Processing {input_path}")
    # Implementation here
    pass
```

10 個實戰 CLAUDE.md 範例(直接複製使用)

以下提供不同類型專案的 CLAUDE.md 範例,可依需求修改後使用:

範例 1:Python 資料科學專案

# Data Science Project - Customer Churn Prediction

## Role
You are a data scientist assistant. Focus on clean, reproducible analysis.

## Tech Stack
- Python 3.11+, pandas, scikit-learn, matplotlib
- Jupyter notebooks in `notebooks/` folder
- Data files in `data/raw/` and `data/processed/`

## Rules
- Always set random_state for reproducibility
- Document data preprocessing steps in notebooks
- Save models with version numbers (model_v1.pkl, model_v2.pkl)
- Use cross-validation before final model evaluation

## Prohibited
- DO NOT overwrite raw data files
- DO NOT commit large data files to git (use .gitignore)
- DO NOT use deprecated sklearn APIs

範例 2:React 前端專案

# React E-commerce Frontend

## Role
You are a React developer. Write modern, performant components.

## Tech Stack
- React 18 + TypeScript
- Vite for build tooling
- TailwindCSS for styling
- React Query for data fetching
- Zustand for state management

## Component Structure
src/
├── components/     # Reusable UI components
├── pages/          # Page-level components
├── hooks/          # Custom hooks
├── store/          # Zustand stores
└── utils/          # Helper functions

## Rules
- Use functional components with hooks (no class components)
- TypeScript types must be defined in separate .types.ts files
- Component files: PascalCase.tsx
- Utility files: camelCase.ts
- CSS: Use Tailwind utility classes, avoid inline styles

## Prohibited
- DO NOT use any, unknown, or implicit types
- DO NOT fetch data in components (use React Query)
- DO NOT put business logic in components (extract to hooks)

範例 3:Go 後端 API

# Go RESTful API - Task Management

## Role
You are a Go backend engineer. Write idiomatic, production-ready code.

## Tech Stack
- Go 1.22+
- Gin web framework
- GORM for ORM
- PostgreSQL database
- JWT for authentication

## Project Structure
cmd/api/          # Main application
internal/
├── handlers/     # HTTP handlers
├── models/       # Database models
├── middleware/   # Custom middleware
└── services/     # Business logic

## Rules
- Follow Effective Go guidelines
- Error handling: always check errors, wrap with context
- Use dependency injection via struct fields
- Tests: use table-driven tests pattern
- Database: use transactions for multi-step operations

## Prohibited
- DO NOT use panic() except in init()
- DO NOT ignore errors with blank identifier
- DO NOT use global variables for config
- DO NOT expose internal types in API responses

範例 4:WordPress 外掛開發

# WordPress Custom Plugin - SEO Toolkit

## Role
You are a WordPress plugin developer. Follow WordPress coding standards.

## Tech Stack
- WordPress 6.5+
- PHP 8.1+
- MySQL 8.0
- WordPress REST API

## Rules
- Prefix all functions with `seotoolkit_`
- Escape output with esc_html(), esc_attr(), esc_url()
- Sanitize input with sanitize_text_field(), wp_kses()
- Use WordPress nonces for form security
- Follow WordPress Coding Standards (WPCS)

## File Structure
includes/           # Core plugin files
admin/             # Admin panel code
public/            # Frontend code
assets/            # CSS/JS files

## Prohibited
- DO NOT use $_GET/$_POST directly (use WordPress sanitization)
- DO NOT write raw SQL (use $wpdb prepared statements)
- DO NOT enqueue scripts without version numbers
- DO NOT ignore WordPress Security Guidelines

範例 5:機器學習訓練腳本

# ML Training Pipeline - Image Classification

## Role
You are an ML engineer. Write scalable training code.

## Tech Stack
- PyTorch 2.1+
- torchvision for datasets
- wandb for experiment tracking
- CUDA 12.1

## Rules
- Use DataLoader with num_workers for parallel data loading
- Log metrics every 100 steps
- Save checkpoints every epoch
- Use mixed precision training (torch.cuda.amp)
- Set seeds for reproducibility

## Training Script Template
- Parse arguments with argparse
- Initialize wandb at start
- Create train/val dataloaders
- Define model, optimizer, loss
- Training loop with tqdm progress bar
- Evaluate on validation set each epoch
- Save best model based on val_loss

## Prohibited
- DO NOT train without validation set
- DO NOT forget to call model.eval() before validation
- DO NOT save models without optimizer state_dict
- DO NOT use large batch sizes without gradient accumulation

進階技巧:多層 CLAUDE.md 設定(全域 + 專案 + 子資料夾)

大型專案常遇到的問題:不同子系統有不同規範(例如前端用 TypeScript、後端用 Python)。Claude Code 支援 多層 CLAUDE.md 設定,越接近檔案的設定優先權越高。

三層架構範例

~/.claude/CLAUDE.md               # 第一層:全域個人偏好
/monorepo-project/CLAUDE.md       # 第二層:專案通用規則
/monorepo-project/frontend/CLAUDE.md  # 第三層:前端子專案規則
/monorepo-project/backend/CLAUDE.md   # 第三層:後端子專案規則

第一層:全域個人偏好(~/.claude/CLAUDE.md)

# Global Personal Preferences

## General Rules (apply to all projects)
- Use UTF-8 encoding for all files
- 2 spaces for indentation (not tabs)
- Unix line endings (LF, not CRLF)
- Meaningful commit messages (imperative mood)

## Tools I Always Use
- VS Code as editor
- Git for version control
- Docker for local development

## My Coding Principles
- DRY (Don't Repeat Yourself)
- Fail fast: validate inputs early
- Explicit is better than implicit

第二層:專案通用規則(/project/CLAUDE.md)

# Monorepo Project - E-commerce Platform

## Project Structure
frontend/     # React TypeScript app
backend/      # Python FastAPI
shared/       # Shared types and utilities
docs/         # Documentation

## Shared Rules (all subprojects)
- API contracts defined in shared/api-spec.yaml
- Commit messages must reference issue number (#123)
- All new features need tests (coverage > 80%)
- Use Conventional Commits format

## Prohibited (Project-wide)
- DO NOT commit credentials or API keys
- DO NOT merge to main without PR approval
- DO NOT deploy on Fridays

第三層:前端子專案規則(/project/frontend/CLAUDE.md)

# Frontend - React TypeScript

## Overrides Parent Rules (if conflict, this takes precedence)
- Indentation: 2 spaces (confirmed, same as global)
- Line length: 100 characters (override project default 80)

## Frontend-Specific Rules
- Components must have PropTypes or TypeScript interfaces
- Use CSS Modules or styled-components (no global CSS)
- Import order: React -> third-party -> internal -> styles
- Asset optimization: images < 100KB, lazy load videos

## Prohibited (Frontend-Specific)
- DO NOT use inline event handlers in JSX
- DO NOT mutate props
- DO NOT use index as key in lists

💡 Claude 讀取順序:全域 → 專案根目錄 → 當前子資料夾,後者會覆蓋前者的相同設定。

多層設定的實際運作流程

當你在 /project/frontend/components/Header.tsx 對話時,Claude 會:

  1. 讀取 ~/.claude/CLAUDE.md(全域)
  2. 讀取 /project/CLAUDE.md(專案層)
  3. 讀取 /project/frontend/CLAUDE.md(子專案層)
  4. 合併三層設定,相同項目以最接近檔案的為準

常見錯誤與避坑指南(5 大地雷)

許多人設定 CLAUDE.md 後發現「Claude 好像沒遵守」,問題通常出在以下五個地雷:

錯誤 1:規則太模糊,AI 無法執行

❌ 錯誤寫法✅ 正確寫法
「寫乾淨的程式碼」「函數不超過 50 行,變數命名使用描述性名稱(如 user_email 而非 ue)」
「注意效能」「資料庫查詢必須使用索引欄位,禁止在迴圈中執行 SQL」
「遵循最佳實踐」「使用 context manager 處理檔案操作(with open()),確保資源正確釋放」

錯誤 2:CLAUDE.md 檔案編碼問題

Windows 用戶常見問題:記事本預設存成 ANSI 編碼,導致中文註解或特殊字元亂碼。

解決方式:

  • 使用 VS Code、Sublime Text 等編輯器,設定存檔編碼為 UTF-8
  • 檔案第一行加入 BOM 標記(VS Code:Save with Encoding → UTF-8 with BOM)

錯誤 3:忘記重新載入專案

修改 CLAUDE.md 後,需要 重新開啟對話 才會生效。如果是全域設定檔,需要重新啟動 Claude Code。

💡 快速驗證方式:開新對話後直接問 Claude:「請告訴我目前專案的 CLAUDE.md 設定內容」,確認它有讀取到。

錯誤 4:規則之間互相衝突

例如:全域設定說「使用 4 空格縮排」,專案設定說「使用 2 空格縮排」,但沒有明確標示「此設定覆蓋全域」,AI 可能混用。

正確做法:

## Indentation (OVERRIDES global setting)
- Use 2 spaces (not 4 spaces from global config)
- Reason: Team standard for this project

錯誤 5:CLAUDE.md 內容過長(超過 4000 字)

CLAUDE.md 會佔用對話的 context window。如果內容超過 4000 字,會壓縮到可用的對話空間,導致 AI 回答變短。

建議長度:

  • 全域設定: 500-800 字(核心原則)
  • 專案設定: 1000-1500 字(詳細規範)
  • 子資料夾設定: 300-500 字(覆蓋項目)

如果需要長篇規範文件,改用 docs/CONTRIBUTING.md 存放,CLAUDE.md 只保留「必須遵守的核心規則」並引用文件路徑。

CLAUDE.md 與記憶套件整合:讓 AI 記住你的習慣

CLAUDE.md 是「專案記憶」,而 Claude Code 記憶與技能套件 是「個人記憶」。兩者結合可以達到:

  • CLAUDE.md 定義專案規範(團隊共享)
  • 記憶套件 記錄你的個人偏好、過去對話的決策、常用的解決方案

實際應用場景

假設你在開發 Python 專案時遇到 SSL 憑證錯誤,你告訴 Claude 用 ssl._create_default_https_context = ssl._create_unverified_context 解決。

  • 只用 CLAUDE.md: 你需要在每個專案的 CLAUDE.md 複製這段解法
  • 加上記憶套件: 套件會記住「阿宥在 macOS 上遇到 SSL 憑證問題時的偏好解法」,自動在所有專案套用

記憶套件包含什麼?

記憶類型內容範例
個人偏好你習慣用 python3 指令、偏好 requests 而非 urllib
歷史決策上次選擇用 PostgreSQL 而非 MySQL 的原因、API 設計風格
常用技能腳本自動發布 WordPress 文章的腳本、SEO 檢查工具
錯誤避坑記錄某個工具在 macOS 上需要特定設定、某 API 的坑點

🎯 記憶套件 + CLAUDE.md 的最佳組合

  • CLAUDE.md: 放團隊共識的規範(可以 commit 到 git,讓所有人遵守)
  • 記憶套件: 放你個人的習慣與歷史經驗(不 commit,只存在你本地)

→ 了解記憶套件完整內容

CLAUDE.md 設定架構圖(ASCII)

以下圖表展示 CLAUDE.md 的三層架構與優先權運作方式:

CLAUDE.md 三層架構與讀取優先權
═══════════════════════════════════════════════════════════════

┌─────────────────────────────────────────────────────────────┐
│  第一層:全域個人偏好(優先權最低)                           │
│  檔案位置:~/.claude/CLAUDE.md                                │
│  ┌───────────────────────────────────────────────────────┐  │
│  │  • 編輯器偏好(VS Code、2 空格縮排)                    │  │
│  │  • 通用禁止行為(不用 os.system、不 commit 金鑰)       │  │
│  │  │  • 個人 coding style(DRY、fail fast)               │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                            ↓ 覆蓋
┌─────────────────────────────────────────────────────────────┐
│  第二層:專案通用規則(優先權中等)                           │
│  檔案位置:/project/CLAUDE.md                                 │
│  ┌───────────────────────────────────────────────────────┐  │
│  │  • 專案架構說明(frontend/ backend/ shared/)          │  │
│  │  • 團隊協作規範(PR review、測試覆蓋率 >80%)          │  │
│  │  • API 設計風格(RESTful、JSON response format)       │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
                            ↓ 覆蓋
┌─────────────────────────────────────────────────────────────┐
│  第三層:子專案規則(優先權最高)                             │
│  檔案位置:/project/frontend/CLAUDE.md                        │
│  ┌───────────────────────────────────────────────────────┐  │
│  │  • 前端專屬技術棧(React、TypeScript、TailwindCSS)    │  │
│  │  • 前端特定禁止行為(不 mutate props、不用 index key) │  │
│  │  • 覆蓋專案設定(行長度改為 100 字元)                  │  │
│  └───────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘

讀取流程(當你在 /project/frontend/App.tsx 對話時):
════════════════════════════════════════════════════════════════

Step 1: 讀取 ~/.claude/CLAUDE.md(基礎規則)
   ↓
Step 2: 讀取 /project/CLAUDE.md(專案層規則,覆蓋相同項目)
   ↓
Step 3: 讀取 /project/frontend/CLAUDE.md(子專案規則,最終覆蓋)
   ↓
Step 4: 合併三層設定 → 產生最終 context
   ↓
Step 5: Claude 依據最終 context 回答你的問題

衝突處理範例:
═══════════════════════════════════════════════════════════════
設定項目          │ 全域      │ 專案      │ 前端子專案 │ 最終值
─────────────────┼──────────┼──────────┼───────────┼─────────
縮排空格          │ 2         │ 4         │ 2          │ 2 ✓
行長度限制        │ 80        │ 80        │ 100        │ 100 ✓
禁止 console.log  │ 是        │ 是        │ 否(開發用)│ 否 ✓
CSS 方案          │ 未定義    │ 未定義    │ Tailwind   │ Tailwind ✓

規則:最接近當前檔案的設定具有最高優先權

FAQ 常見問題

Q1. CLAUDE.md 支援哪些格式?可以用 YAML 嗎?

目前 Claude Code 只支援 Markdown 格式(.md)。不支援 YAML、JSON 或其他格式。檔案必須命名為 CLAUDE.md(全大寫),小寫 claude.md 不會被讀取。

Q2. 修改 CLAUDE.md 後需要做什麼才能生效?

專案層級 CLAUDE.md: 重新開啟對話(關閉當前對話視窗,再開新對話)。
全域 CLAUDE.md: 需要重新啟動 Claude Code 應用程式。
驗證方式:開新對話後問「請告訴我目前的 CLAUDE.md 設定內容」。

Q3. CLAUDE.md 可以放在子資料夾嗎?有幾層限制?

可以。Claude Code 支援 無限層級 的 CLAUDE.md,每層都會被讀取,優先權:子資料夾 > 專案根目錄 > 全域。實務上建議不超過 3 層(全域、專案、子專案),太多層會讓設定難以追蹤。

Q4. CLAUDE.md 會不會洩漏給其他人?

全域 CLAUDE.md(~/.claude/): 只存在你本地電腦,不會上傳到 Anthropic 伺服器永久儲存,每次對話臨時載入後即丟棄。
專案 CLAUDE.md: 如果你 commit 到 git,協作者會看到。建議:敏感資訊(API keys、內部規範)不要寫在 CLAUDE.md,改用 .env 或內部文件。

Q5. Karpathy 的方法適合初學者嗎?

非常適合。Karpathy 強調「給 AI 清楚的規則,而非假設它會猜」,這對初學者尤其重要。建議從簡單的 CLAUDE.md 開始(10-15 行基本規則),用 1-2 週後根據實際遇到的問題逐步補充。不要一開始就寫 100 行規則,AI 和你都會被淹沒

結語:從今天開始建立你的 CLAUDE.md

CLAUDE.md 不是一次寫完的文件,而是隨專案成長逐步累積的「協作知識庫」。Karpathy 的方法告訴我們:AI 不會讀心術,清楚的規則讓協作更高效

立即行動的三步驟:

  1. 今天下班前: 在你最常用的專案根目錄建立 CLAUDE.md,寫入 5-10 條核心規則
  2. 本週內: 每次發現 Claude 沒做對的地方,問自己「我有沒有在 CLAUDE.md 明確寫出這個規則?」,有漏的立刻補上
  3. 一個月後: 回顧你的 CLAUDE.md,刪掉從未觸發的規則,保留真正有用的核心設定

搭配 Claude Code 記憶與技能套件,你的 AI 協作效率將不只是「能用」,而是「比人類助理更懂你」。

💡 記住 Karpathy 的金句:「Explicit is better than implicit. AI needs clear rules, not magic.」

資料來源:Karpathy LLM101n GitHubAnthropic Claude Project Knowledge 文件

更多實戰範例:特定場景的 CLAUDE.md 設定

以下補充 5 個進階場景的設定範例,涵蓋不同開發情境:

範例 6:DevOps 自動化腳本專案

# DevOps Automation Scripts

## Role
You are a DevOps engineer writing production automation scripts.

## Tech Stack
- Bash 5.x for shell scripts
- Python 3.11+ for complex automation
- Ansible for configuration management
- Terraform for infrastructure as code

## Script Standards
- Shebang: #!/usr/bin/env bash
- Error handling: set -euo pipefail at top of every script
- Logging: timestamp + severity level + message
- Idempotency: scripts must be safe to run multiple times

## Security Rules
- All credentials from environment variables or secret manager
- Validate inputs before executing system commands
- Use sudo only when absolutely necessary
- Log all destructive operations before execution

## Prohibited
- DO NOT use rm -rf without confirmation prompt
- DO NOT store credentials in scripts
- DO NOT execute commands from unvalidated user input
- DO NOT skip error handling for system commands

範例 7:Mobile App 開發(React Native)

# React Native E-commerce App

## Role
You are a mobile app developer. Prioritize performance and UX.

## Tech Stack
- React Native 0.73+
- TypeScript strict mode
- React Navigation for routing
- React Native MMKV for storage (not AsyncStorage)
- React Query for API calls

## Mobile-Specific Rules
- Images: use WebP format, provide @2x and @3x variants
- Lists: use FlatList with optimizations (windowSize, removeClippedSubviews)
- Navigation: avoid deep nesting (max 3 levels)
- Android: handle back button behavior
- iOS: respect Safe Area insets

## Performance Requirements
- App launch: < 2 seconds on mid-range devices
- Screen transitions: 60 FPS (use useNativeDriver: true)
- Bundle size: < 15MB after optimization

## Prohibited
- DO NOT use ScrollView for long lists (use FlatList)
- DO NOT render heavy components in navigator screens directly
- DO NOT forget to unsubscribe from listeners
- DO NOT use inline functions in render props

範例 8:遊戲開發(Unity C#)

# Unity 3D Game Project - Action RPG

## Role
You are a Unity game developer. Write optimized, maintainable code.

## Tech Stack
- Unity 2023.2+
- C# 11 with .NET Standard 2.1
- Unity Input System (not legacy Input)
- Addressables for asset management
- DOTween for animations

## Code Structure
Assets/Scripts/
├── Core/           # Game managers, singletons
├── Player/         # Player controller, inventory
├── Enemies/        # AI, spawning
├── UI/             # Menus, HUD
└── Utilities/      # Helpers, extensions

## Unity-Specific Rules
- MonoBehaviour lifecycle: Awake → OnEnable → Start
- Use object pooling for frequently spawned objects
- Cache GetComponent calls in Awake/Start
- Coroutines for delays, async/await for long operations
- ScriptableObjects for game data (not static classes)

## Performance Rules
- Target: 60 FPS on mid-range hardware
- Update vs FixedUpdate: physics in FixedUpdate only
- Avoid FindObjectOfType in Update/FixedUpdate
- Use LayerMask for raycasts (not hit all colliders)

## Prohibited
- DO NOT use Find or GameObject.Find in loops
- DO NOT use Camera.main repeatedly (cache it)
- DO NOT instantiate/destroy every frame (use pooling)
- DO NOT put heavy logic in Update (use events/observers)

範例 9:資料庫管理與最佳化

# Database Administration - PostgreSQL

## Role
You are a database administrator. Focus on performance and reliability.

## Tech Stack
- PostgreSQL 16
- pgAdmin 4 for management
- pg_stat_statements for query analysis
- Patroni for high availability

## Schema Design Rules
- Primary keys: BIGSERIAL for large tables, UUID for distributed systems
- Indexes: create indexes on foreign keys and WHERE clause columns
- Constraints: use CHECK constraints for data validation
- Partitioning: use for tables > 10M rows

## Query Optimization
- Always use EXPLAIN ANALYZE for slow queries
- Avoid SELECT * (specify columns)
- Use CTEs for complex queries (with ... as ...)
- Batch operations: use unnest() for bulk inserts

## Backup & Recovery
- Daily full backups + continuous WAL archiving
- Test restore procedures monthly
- Document RTO (Recovery Time Objective): < 1 hour

## Prohibited
- DO NOT create indexes without analyzing query patterns first
- DO NOT use LIKE '%keyword%' (no leading wildcard, ruins index)
- DO NOT run DDL changes in production without backup
- DO NOT grant superuser privileges to application users

範例 10:技術寫作與文件專案

# Technical Documentation Project

## Role
You are a technical writer. Write clear, accurate documentation.

## Tech Stack
- Markdown for content
- MkDocs or Docusaurus for site generation
- Mermaid for diagrams
- Vale for style linting

## Writing Standards
- Audience: developers with 1-2 years experience
- Tone: professional but friendly, avoid jargon
- Structure: overview → prerequisites → step-by-step → troubleshooting
- Code examples: runnable, include expected output

## File Organization
docs/
├── getting-started/    # Installation, quickstart
├── guides/             # How-to guides
├── reference/          # API reference
└── troubleshooting/    # Common issues

## Markdown Style
- Headings: sentence case (not title case)
- Lists: parallel structure (all items same grammatical form)
- Code blocks: always specify language (```python not ```)
- Links: descriptive text (not "click here")

## Prohibited
- DO NOT assume reader knowledge without prerequisites section
- DO NOT use ambiguous pronouns (it, that, this) without antecedent
- DO NOT mix imperative and declarative sentences in steps
- DO NOT include outdated version numbers (use "latest" or date)

💡 這些範例可直接複製到專案中,再根據實際需求調整技術棧與規則。

CLAUDE.md 除錯技巧:為什麼 AI 沒遵守我的規則?

當你發現 Claude 沒有按照 CLAUDE.md 的設定執行時,可以用以下方法診斷問題:

除錯步驟 1:確認 Claude 有讀取到 CLAUDE.md

在新對話中直接問:

請告訴我目前專案的 CLAUDE.md 設定內容,列出前 5 條規則。

如果 Claude 回答「我沒有找到 CLAUDE.md」,檢查:

  • 檔案名稱是否正確(必須是 CLAUDE.md,全大寫)
  • 檔案是否在專案根目錄或 ~/.claude/
  • 檔案編碼是否為 UTF-8

除錯步驟 2:檢查規則是否夠明確

AI 無法執行模糊的指示。對比以下兩種寫法:

❌ 模糊寫法✅ 明確寫法
「盡量使用現代 ES6+ 語法」「使用箭頭函數取代 function 關鍵字、使用解構賦值、使用模板字串取代字串拼接」
「重視安全性」「所有 SQL 查詢必須使用參數化查詢,禁止字串拼接 SQL;使用者輸入必須經過 sanitize_text_field() 處理」

除錯步驟 3:檢查規則之間是否衝突

如果全域 CLAUDE.md 說「使用 4 空格縮排」,專案 CLAUDE.md 說「使用 2 空格縮排」,但沒有明確標示「覆蓋全域」,Claude 可能混用。

解決方式: 在專案 CLAUDE.md 加上明確覆蓋說明:

## Indentation (OVERRIDES global setting)
This project uses 2 spaces, not the global default of 4 spaces.
Reason: Team agreed on this standard in meeting 2026-03-15.

除錯步驟 4:驗證規則的可執行性

有些規則 Claude 物理上無法執行。例如:

  • ❌ 「確保所有測試通過」→ Claude 無法執行測試(可以寫測試碼,但不能執行)
  • ✅ 「為每個函數寫對應的 pytest 測試,放在 tests/ 資料夾」→ 可執行

除錯步驟 5:使用「驗證對話」測試設定

建立一個測試對話,故意讓 Claude 違反你的規則,看它會不會自我修正:

你:請寫一個 Python 函數讀取檔案。
Claude:(如果生成的程式碼用 os.system 而你的 CLAUDE.md 禁止這樣做)
你:這段程式碼是否符合專案的 CLAUDE.md 規則?
Claude:(應該要自己發現違反規則並修正)

如果 Claude 沒有自我修正,代表規則寫得不夠清楚或沒被讀取到。

💡 除錯黃金法則:如果 Claude 連續 3 次都違反同一條規則,問題不在 AI,而是你的規則不夠明確。

CLAUDE.md 與 CI/CD 整合:自動驗證程式碼規範

CLAUDE.md 定義的規則,可以透過 CI/CD pipeline 自動檢查,確保團隊成員(包括 AI 生成的程式碼)都遵守:

整合方式 1:Linting 工具檢查

將 CLAUDE.md 中的程式碼規範轉換為 linter 設定檔:

CLAUDE.md 規則對應的 Linter 設定
「行長度限制 100 字元」.flake8: max-line-length = 100
「禁止使用 print() 做 logging」pylint: 自訂規則禁止 print 在非測試檔案
「所有函數需要 type hints」mypy: disallow_untyped_defs = True

整合方式 2:GitHub Actions 自動檢查範例

name: Code Style Check

on: [push, pull_request]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      
      - name: Install linters
        run: |
          pip install flake8 mypy black
      
      - name: Check code formatting (Black)
        run: black --check --line-length 100 .
      
      - name: Check code style (Flake8)
        run: flake8 --max-line-length=100 .
      
      - name: Check type hints (mypy)
        run: mypy --disallow-untyped-defs .
      
      - name: Verify CLAUDE.md compliance
        run: |
          # 自訂腳本檢查特定規則(如禁止 os.system)
          python scripts/check_claude_rules.py

整合方式 3:Pre-commit Hook

在本地 commit 前自動檢查,防止違反 CLAUDE.md 的程式碼進入 repo:

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/psf/black
    rev: 23.12.1
    hooks:
      - id: black
        args: [--line-length=100]
  
  - repo: https://github.com/pycqa/flake8
    rev: 7.0.0
    hooks:
      - id: flake8
        args: [--max-line-length=100]
  
  - repo: local
    hooks:
      - id: check-prohibited-functions
        name: Check CLAUDE.md prohibited functions
        entry: python scripts/check_prohibited.py
        language: system
        types: [python]

安裝後,每次 git commit 都會自動檢查,違反規則則阻止 commit。

💡 CI/CD 整合讓 CLAUDE.md 從「建議」升級為「強制規範」,確保人類與 AI 寫的程式碼都符合標準。

團隊協作最佳實踐:如何讓整個團隊用好 CLAUDE.md

CLAUDE.md 不只是個人工具,更是團隊協作的規範文件。以下是讓整個團隊有效使用的方法:

實踐 1:在 README 中說明 CLAUDE.md 的作用

新成員加入專案時,應該能快速理解 CLAUDE.md 的目的:

# Project XYZ

## For AI-Assisted Development
This project includes a `CLAUDE.md` file that defines coding standards 
and project-specific rules for Claude Code and other AI assistants.

**For human developers:** These rules also serve as our coding guidelines.
**For AI tools:** Read `CLAUDE.md` to understand project conventions.

To validate your code matches CLAUDE.md rules, run:
```bash
pre-commit run --all-files
```

實踐 2:定期審查與更新 CLAUDE.md

建議每個 sprint 或每月審查一次:

  1. 收集違規案例: 記錄團隊成員或 AI 違反哪些規則
  2. 評估規則有效性: 哪些規則從未被觸發?(可以刪除)
  3. 新增新規則: 最近遇到什麼新問題需要加入規範?
  4. 更新範例: 實際專案中的好程式碼可以加入 CLAUDE.md 作為範例

實踐 3:用 CLAUDE.md 統一 AI 工具行為

如果團隊成員使用不同 AI 工具(Claude、Cursor、GitHub Copilot),CLAUDE.md 可以作為共同規範:

  • Claude Code: 直接讀取 CLAUDE.md
  • Cursor:.cursorrules 中引用 CLAUDE.md 內容
  • GitHub Copilot: 在專案根目錄加 .github/copilot-instructions.md(GitHub 2026 新功能)

三個檔案內容保持一致,確保不同工具生成的程式碼風格統一。

實踐 4:Code Review 時檢查 CLAUDE.md 合規性

在 PR review checklist 加入:

## Code Review Checklist

- [ ] 功能符合需求
- [ ] 測試覆蓋率 >80%
- [ ] 程式碼遵守 CLAUDE.md 規範(特別檢查禁止行為清單)
- [ ] 如果違反 CLAUDE.md,是否有充分理由並記錄在 commit message?

實踐 5:記錄例外情況與豁免

有時候需要違反規則(如效能關鍵路徑),應該在 CLAUDE.md 記錄:

## Exceptions to Rules

### Use of `eval()` (normally prohibited)
- **Where:** src/formula_engine.py line 234
- **Reason:** User-defined formulas, sandboxed environment
- **Approved by:** Tech Lead, 2026-04-01
- **Security review:** Passed, input validation in place

這樣 AI 看到這段程式碼時不會誤判為錯誤,團隊成員也能理解脈絡。

💡 CLAUDE.md 是「活的文件」:隨專案演進持續更新,而非寫一次就忘記。

進階應用:CLAUDE.md 的隱藏功能

除了基本的規則定義,CLAUDE.md 還有一些進階用法,可以進一步提升 AI 協作效率:

隱藏功能 1:定義專案術語表

專案中有特殊術語時,可以在 CLAUDE.md 建立術語表,避免 AI 誤解:

## Project Glossary

- **Widget:** In this project, refers to dashboard UI components, not generic UI elements
- **Pipeline:** ETL data processing workflow, not CI/CD pipeline
- **Agent:** Autonomous background worker process, not AI agent
- **Session:** User login session stored in Redis, expires after 30 minutes

When I mention these terms, use the above definitions, not general meanings.

隱藏功能 2:定義決策樹

對於常見的技術選擇,可以在 CLAUDE.md 預先定義決策邏輯:

## Decision Trees

### When to use caching?
- List query with >1000 results → cache for 5 minutes
- User profile data → cache for 1 hour
- Real-time data (stock prices) → do not cache
- Static content (images, CSS) → cache forever with versioned URLs

### Which database query method?
- Single record by ID → get_object_or_404()
- Multiple records with filters → Model.objects.filter()
- Complex joins → raw SQL with comments explaining logic
- Aggregate calculations → Django ORM aggregate()

這樣 Claude 面對選擇時會依據專案脈絡做決策,而非用通用最佳實踐。

隱藏功能 3:連結外部文件

如果專案有詳細的技術文件,可以在 CLAUDE.md 引用:

## Reference Documents

For detailed information, refer to:
- API Design: docs/api-design-guide.md
- Database Schema: docs/database-schema.md
- Deployment Process: docs/deployment.md
- Security Checklist: docs/security-checklist.md

If I ask about these topics, read the corresponding document first.

Claude 會在需要時主動讀取這些文件,減少你重複說明的次數。

隱藏功能 4:定義「優先順序規則」

當規則之間有衝突時,告訴 Claude 哪個優先:

## Priority When Rules Conflict

If you face conflicting requirements, prioritize in this order:

1. **Security** - Never compromise security for other goals
2. **Correctness** - Code must be functionally correct
3. **Performance** - Optimize only after correctness is ensured
4. **Readability** - Prefer clear code over clever code
5. **Consistency** - Follow existing patterns in the codebase

Example: If a performance optimization makes code less readable,
discuss trade-offs with me before implementing.

💡 這些隱藏功能讓 CLAUDE.md 從「規則清單」進化為「專案知識庫」,Claude 能更深入理解專案脈絡。


🤖 購買 Claude Code 記憶與技能套件,讓 Claude Code 記住你 →

解壓縮 → 拖入 Claude Code → 輸入序號,5 分鐘完成安裝

✅ 套件內含功能:

🧠 雙層記憶系統(跨對話長期記憶,越用越懂你)

🔄 智慧規則載入(自動選最相關規則,省最高 89% Token)

📊 品質評估閘門(文章/程式碼送出前自動評分把關)

⚡ 自動學習任務框架(自動記錯誤→優化流程→持續進化)

🛠️ 11 個內建技能(知識餵養・網頁爬取・每日收尾等)

☁️ Google Drive 雲端同步引導

🔒 單一裝置授權,資料不外傳

原價 NT$1,288

NT$600

前 100 名限定優惠價格

每組序號第一裝置限一用・不可轉讓或分享

Compare Listings

TitlePriceStatusTypeAreaPurposeBedroomsBathrooms

Compare