如何精簡 Claude Code 的 CLAUDE.md,改善指令遵循
Your CLAUDE.md Is Too Long: What to Cut So Claude Code Follows It
文章建議精簡 Claude Code 的 CLAUDE.md,只保留刪除後可能令 Claude 犯錯的規則,並把其他內容移至更合適的位置。Anthropic 文件建議每個 CLAUDE.md 少於 200 行;格式規則可改用 hook,多步驟程序放入 skill,特定路徑規則放到 .claude/rules/,個人設定則放入 CLAUDE.local.md。
You added a rule to your CLAUDE.md. Claude Code ignored it. So you added it again, in capitals, a bit further down. A month later the file is 600 lines long, and Claude still forgets to run the tests.
The fix is almost never another line. It's fewer lines. Anthropic's own Claude Code best practices put it bluntly: "Bloated CLAUDE.md files cause Claude to ignore your actual instructions!" This article walks through what to cut, where each cut line should go instead, and how to check the result.
Why a long CLAUDE.md gets ignored
Three facts from the Claude Code memory docs explain most of the problem:
-
It's context, not configuration.
CLAUDE.mdis delivered as a user message after the system prompt. Claude reads it and tries to follow it, but the docs say there's no guarantee of strict compliance, especially for vague or conflicting instructions. -
Length costs you twice. The docs suggest keeping each
CLAUDE.mdfile under 200 lines, because longer files consume more context and reduce adherence. Every session pays for every line, whether it's relevant to the task or not. - Contradictions get resolved at random. If two instructions conflict, the docs say Claude may pick one arbitrarily. The longer the file, the more likely that two lines disagree.
The best-practices page also gives the symptom to watch for: if Claude keeps doing something despite a rule against it, the file is probably too long and the rule is getting lost.
How long are real files? One developer on X reported reading the AGENTS.md and CLAUDE.md files in 1,414 active open-source repos and found a median of 909 words, about a four-minute read. That's one person's sample, not a study, but it matches what a lot of people describe: files that grow a line at a time and never shrink.
The one-line test
Anthropic's best practices give a single question to ask of every line:
"Would removing this cause Claude to make mistakes?"
If the answer is no, cut it. That's the whole method. The rest of this article is about the two follow-up questions: what usually fails the test, and where do the lines that pass the test but don't belong in every session go.
A before-and-after example
Here's an illustrative bloated file. It's a made-up example, but every line in it is the kind of thing that shows up in real ones:
# CLAUDE.md
You are a senior full-stack engineer. Think step by step and write clean,
maintainable, well-documented code. Always follow best practices.
## Project
This is a Next.js app. The src folder contains the source code. The
components folder contains React components. The utils folder contains
utility functions. (...40 more lines describing folders...)
## Code style
- Use 2 spaces for indentation
- Use semicolons
- Use double quotes
- Sort imports alphabetically
## Database migrations
1. Run `pnpm db:generate`
2. Review the SQL in drizzle/
3. Run `pnpm db:migrate` against the local DB
4. (...12 more steps...)
## API routes
- All handlers in src/app/api must validate input with zod
- Return errors as { error: { code, message } }
## My setup
- My local DB runs on port 5433
- Use my test account test+dev@example.com
## Commands
- Use pnpm, not npm
- Run `pnpm test` before committing
Now apply the test, section by section.
What to cut, and where it goes
1. Personality and generic advice: delete. "Senior engineer", "think step by step", "write clean code", "follow best practices". The best-practices page lists "self-evident practices like 'write clean code'" under things to exclude. Removing them won't cause a single mistake.
2. Things Claude can read from the code: delete. The folder tour fails the test, because Claude can list the directory itself. The same exclude list names "anything Claude can figure out by reading code" and "file-by-file descriptions of the codebase". Keep only what isn't obvious from the code, such as an architectural decision or a gotcha.
3. Formatting rules a tool already enforces: move them to a hook. Indentation, semicolons and quote style belong to your formatter. The docs recommend a hook for anything that must happen every time, because hooks run as shell commands at fixed points and apply regardless of what Claude decides. This is the auto-format hook from the hooks guide, added to .claude/settings.json:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | xargs npx prettier --write"
}
]
}
]
}
}
Four lines of style rules become zero lines of context, and formatting no longer depends on Claude remembering.
4. Multi-step procedures: move them to a skill. The 16-step migration recipe matters maybe once a week. The memory docs say that if an entry is a multi-step procedure, it belongs in a skill, which Claude loads on demand instead of in every session.
5. Rules for one part of the codebase: move them to a path-scoped rule. The zod and error-format rules only matter in API routes. Put them in .claude/rules/api.md with a paths field in the frontmatter, and they load only when Claude reads or edits a matching file:
---
paths:
- "src/app/api/**/*.ts"
---
# API route rules
- Validate all input with zod
- Return errors as { error: { code, message } }
6. Personal settings: move them to CLAUDE.local.md. Your port and your test account aren't team knowledge. The docs describe CLAUDE.local.md at the project root for personal project-specific preferences. Add it to .gitignore so it isn't committed.
One trap: don't "shrink" the file by splitting it into @path imports. The docs note that imports help you organize a long file but don't reduce its context cost, because imported files also load at launch.
The result
# CLAUDE.md
## Commands
- Package manager: pnpm (never npm or yarn)
- Test: `pnpm test` (run before every commit)
- Migrations: use the db-migrations skill, never edit drizzle/ by hand
## Architecture
- Server components by default; add "use client" only for interactivity
- All database access goes through src/lib/db; no queries in components
Every remaining line passes the test: delete it, and Claude could plausibly get it wrong. The architecture lines are examples of what you'd keep, so swap in your own project's real decisions.
Notice the instructions are also concrete enough to check. The memory docs contrast "Run npm test before committing" with "Test your changes", and "Use 2-space indentation" with "Format code properly". If you can't tell whether Claude followed a line, Claude can't either.
Check that it worked
Trimming is a hypothesis. Test it:
-
Confirm what loaded. Run
/contextin a session and check the list under Memory files. If a file isn't there, Claude can't see it. -
Run an audit.
/doctor prompt-audit(Claude Code v2.1.283 or later, per the docs) looks for instructions written for older models, references to files or commands that don't exist, and files that contradict each other. It proposes edits and changes nothing until you ask. -
Watch behavior, not the file. The best-practices page says to treat
CLAUDE.mdlike code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude's behavior actually shifts. - Use emphasis sparingly. If one rule keeps getting skipped, the docs suggest adding "IMPORTANT" to that line alone. Emphasize many lines and none of them stands out.
And when should a line be added back? The memory docs give a good rule: when Claude makes the same mistake a second time, when code review catches something Claude should have known, or when you type the same correction you typed last session.
A 20-minute trim checklist
- Is the file under 200 lines?
- Did every line pass "Would removing this cause Claude to make mistakes?"
- Is there any personality or "best practices" filler left?
- Are formatting rules enforced by a formatter or hook instead of prose?
- Are multi-step procedures in skills, and area-specific rules in
.claude/rules/withpaths? - Are personal settings in a gitignored
CLAUDE.local.md? - Did you check
/contextand run/doctor prompt-audit?
A short CLAUDE.md isn't a minimalist style choice. It's what makes the rules you keep actually work.
If you want the essentials on a few pages, I put them in a free cheat sheet: CLAUDE.md Quick-Start Cheat Sheet. It covers what belongs in the file, what to leave out, the one-line test and a map of the configuration stack, in six pages. When you want the full reference, with slash commands, subagents, hooks, skills and plugins, three real-world configuration walkthroughs, the nine most common mistakes and a 30-day plan, the next step is CLAUDE.md: The Complete Claude Code Configuration Guide.
This article was written with the assistance of AI and reviewed by the author.
來源:DEV Community · dev.to