Hooks 与 settings.json 配方
可直接套用的配方,适用于 settings.json、权限和 hooks。请将命令调整为适配你的技术栈。
起步项目 settings.json
.claude/settings.json(提交到仓库,团队共享):
{
"permissions": {
"allow": [
"Read",
"Bash(npm run test:*)",
"Bash(npm run lint)",
"Bash(git status)",
"Bash(git diff:*)"
],
"ask": ["Bash(npm install:*)", "Write"],
"deny": ["Read(./.env)", "Read(./**/*.pem)", "Bash(git push --force:*)"]
}
}
把个人/特定机器的覆盖配置放进 .claude/settings.local.json(被 git 忽略)。
编辑后自动格式化
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "npx prettier --write \"$CLAUDE_FILE_PATH\" 2>/dev/null || true" }
]
}
]
}
}
完成前的质量门禁
在测试通过之前阻止「完成」(仅为示意 —— 请按文档将其接入 Stop/完成前事件):
{
"hooks": {
"Stop": [
{ "hooks": [ { "type": "command", "command": "npm test --silent" } ] }
]
}
}
安全防护(阻止编辑受保护路径)
{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "case \"$CLAUDE_FILE_PATH\" in *secrets*|*.env|*/vendor/*) echo 'blocked: protected path'; exit 1;; esac" }
]
}
]
}
}
:::tip 让 hooks 保持快速且幂等 它们会频繁运行。务必让它们执行迅速、可安全重复执行,并且只在出现真正问题时才发出提示。 :::