Hooks
Hooks 实战:每次提交前自动检查
用 pre-commit hook 让 Claude 强制跑 lint / typecheck,告别 CI 红。
6 分钟2026-05-25
为什么需要 hook
Skill 是"Claude 主动选择",Hook 是"强制流程"。常见用法:
- pre-commit — 提交前必跑 lint / build
- on-edit — 改完文件自动 reformat
- on-shell — 跑 shell 命令前过滤危险动作(
rm -rf等)
Hook 失败时,Claude 会被告知"这一步失败了",然后可以决定继续 / 修复 / 报错给用户。
配置位置
.claude/settings.json(项目级,进 git)或 ~/.claude/settings.json(全局,不进 git)。
最小可用 pre-commit hook
{
"hooks": {
"pre-commit": [
{
"name": "lint",
"command": "bun run lint",
"blocking": true
},
{
"name": "build",
"command": "bun run build",
"blocking": true
}
]
}
}
字段含义:
- name — log 里的标识
- command — 跑啥
- blocking —
true表示失败就 abort commit;false只警告
在 Claude Code 里看效果
> 帮我把这个 bug 修了然后提交
[Claude 改完代码]
> [hook: lint] 跑 bun run lint... ✓
> [hook: build] 跑 bun run build... ✗ TypeScript 报错: foo.tsx:23 ...
> 我看到 build 失败了,是 foo.tsx 第 23 行的类型错。我先把这个修了再提交。
[Claude 继续修]
Hook 失败 → Claude 主动接住 → 继续修。不需要你手动干预。
进阶:条件 hook
只在改了 .ts/.tsx 文件时跑 typecheck:
{
"hooks": {
"pre-commit": [
{
"name": "typecheck",
"command": "bun run typecheck",
"blocking": true,
"when": {
"files_changed": ["**/*.ts", "**/*.tsx"]
}
}
]
}
}
防误删 hook
{
"hooks": {
"pre-bash": [
{
"name": "block-destructive",
"command": "echo \"{{command}}\" | grep -qE 'rm -rf|git push --force|drop database'",
"blocking": true,
"on_success": "abort"
}
]
}
}
Claude 跑 shell 之前先检查。匹配到危险关键字就 abort。
注意事项
- blocking hook 让 Claude 慢 — 每次都跑全量 build 可能 10s+。把重的放
pre-commit,轻的放on-edit - 不要
--no-verify绕过 — 全局 CLAUDE.md 明确禁止。hook 失败要修,不是跳过 - hook 输出要简短 — Claude 把它当 context 加载,太长会污染对话
一句话总结
hook 不是 PR review 的替代,是给 Claude 装的"机械护栏"。