CLAUDE.md 里的规则,Claude 「会尽量遵守」。Hooks 不一样——100% 确定执行。
每次 Claude 编辑文件,Prettier 自动跑;每次执行危险命令,脚本自动拦截——和 Claude 「想不想」无关。
Hooks 生命周期
| 事件 | 触发时机 | 用途 |
|---|---|---|
PreToolUse | 工具调用前 | 拦截危险操作 |
PostToolUse | 工具调用后 | 格式化、lint |
SessionStart | 会话开始 | 初始化 |
SessionEnd | 会话结束 | 清理、汇报 |
Notification | Claude 需要关注时 | 推送通知 |
配置位置
json
// .claude/settings.json(项目级,团队共享)
{
"hooks": {
"PostToolUse": [...],
"PreToolUse": [...]
}
}会话中 /hooks 查看和管理。让 Claude 帮你写:
text
"Write a hook that runs eslint after every file edit"Hook 1:每次编辑后自动 Prettier
json
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "npx prettier --write \"CLAUDE_FILE_PATH_VAR\" 2>/dev/null || true"
}]
}]
}
}|| true 防止 hook 失败阻断 Claude。
Hook 2:拦截危险命令
防止 rm -rf、drop table 等破坏性操作:
json
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "if echo \"TOOL_INPUT_VAR\" | grep -qE 'rm -rf|drop table|truncate'; then echo 'BLOCKED' >&2; exit 2; fi"
}]
}]
}
}Hook 返回 exit 2,Claude 不会执行。可扩展:force push|DELETE FROM|shutdown
Hook 3:保护特定路径
不允许写入 migrations/、.env、secrets/:
json
{
"PreToolUse": [{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "echo \"CLAUDE_FILE_PATH_VAR\" | grep -qE '(migrations|.env|secrets)/' && echo 'BLOCKED: protected path' >&2 && exit 2 || exit 0"
}]
}]
}Hook 4:任务完成通知
macOS 系统通知:
json
{
"Notification": [{
"hooks": [{
"type": "command",
"command": "osascript -e 'display notification \"Claude needs attention\" with title \"Claude Code\"'"
}]
}]
}Hook 5:ESLint 自动修复
json
{
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "npx eslint --fix \"CLAUDE_FILE_PATH_VAR\" 2>/dev/null || true"
}]
}]
}链式叠加(Prettier + ESLint 同时跑):
json
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "npx prettier --write \"CLAUDE_FILE_PATH_VAR\" 2>/dev/null || true" },
{ "type": "command", "command": "npx eslint --fix \"CLAUDE_FILE_PATH_VAR\" 2>/dev/null || true" }
]
}Hook 6:SessionEnd 保存日志
json
{
"SessionEnd": [{
"hooks": [{
"type": "command",
"command": "echo \"$(date): Claude session ended\" >> ~/claude-sessions.log"
}]
}]
}可用环境变量
| 变量 | 说明 |
|---|---|
CLAUDE_FILE_PATH | 当前操作的文件路径 |
TOOL_INPUT | 工具调用的完整输入 |
CLAUDE.md 建议 vs Hooks:选哪个?
| 场景 | CLAUDE.md | Hooks |
|---|---|---|
| 风格「建议」 | ✅ | ❌ |
| 必须执行的操作 | ❌ | ✅ |
| 拦截危险命令 | ❌ | ✅ |
| 自动格式化 | ❌ | ✅ |
原则:建议 Claude 的放 CLAUDE.md;必须发生的用 Hooks。
来源:Claude Code Hooks 官方文档 | builder.io | 整理:ClaudeEagle