# 另一个实用 Hook

URL: https://caijiao.org/claude-code-in-action/18-another-useful-hook
Source: docs/claude-code-in-action/18-another-useful-hook.md
Description: 介绍 Git 提交前自动运行检查的 Hook 实现，帮助保持代码质量和提交历史整洁

原文链接：[https://anthropic.skilljar.com/claude-code-in-action/303249](https://anthropic.skilljar.com/claude-code-in-action/303249)

**标签：** 讲义

---

本节介绍另一个非常实用的 Hook：Git 提交前自动运行检查。这个 Hook 可以帮助你保持提交历史的整洁和质量。

## 场景

我们希望在每次提交前自动运行以下检查：

1. 代码格式化
2. Lint 检查
3. 测试（快速版）

## 实现

```json
{
  "hooks": {
    "BeforeAgentLoop": [
      {
        "name": "Pre-commit checks",
        "command": "npm run pre-commit-checks",
        "runOnlyWhen": "userMessage匹配 /^(git commit|git push|commit|push)/i",
        "description": "提交前运行检查",
        "timeout": 300000
      }
    ]
  }
}
```

## package.json 配置

```json
{
  "scripts": {
    "pre-commit-checks": "npm run format:check && npm run lint:fast && npm run test:fast"
  },
  "devDependencies": {
    "husky": "^8.0.0"
  }
}
```

## 详细说明

- `format:check`：检查代码格式，不自动修复
- `lint:fast`：快速 lint，跳过耗时检查
- `test:fast`：运行快速测试，跳过覆盖率

## 注意事项

1. 这个 Hook 只在检测到提交相关命令时触发
2. 设置合理的超时时间
3. 确保快速检查不会遗漏重要问题

## 进阶：智能跳过

对于大型项目，可以添加逻辑跳过不必要的检查：

```bash
# 只检查变更的文件
npm run lint:changed
npm run test:changed
```

这样可以大幅减少检查时间，同时保持代码质量。

---

**下一节：** [19 Claude Code SDK](./19-the-claude-code-sdk)
