教程 claude-code-in-action tutorial

实用的 Hooks

原文链接:https://anthropic.skilljar.com/claude-code-in-action/303248

标签: 视频 + 讲义


本节分享一些在真实项目中非常实用的 Hook 示例,你可以直接采用或根据需要进行修改。

1. 自动格式化 Hook

在每次修改前自动格式化代码:

json
{
  "hooks": {
    "BeforeModify": [
      {
        "name": "Format code",
        "command": "npm run format",
        "description": "修改前自动格式化代码"
      }
    ]
  }
}

2. 类型检查 Hook

修改 TypeScript 文件后检查类型:

json
{
  "hooks": {
    "AfterModify": [
      {
        "name": "Type check",
        "command": "npx tsc --noEmit",
        "runOnlyWhen": "changedFiles匹配 **/*.ts **/*.tsx",
        "description": "修改后检查 TypeScript 类型"
      }
    ]
  }
}

3. 测试 Hook

修改测试文件后自动运行测试:

json
{
  "hooks": {
    "AfterModify": [
      {
        "name": "Run tests",
        "command": "npm test -- --run",
        "runOnlyWhen": "changedFiles匹配 **/*.test.ts **/*.test.tsx",
        "description": "修改测试文件后运行测试",
        "timeout": 180000
      }
    ]
  }
}

4. ESLint Hook

在提交前运行 ESLint:

json
{
  "hooks": {
    "BeforeModify": [
      {
        "name": "ESLint check",
        "command": "npx eslint . --max-warnings=0",
        "runOnlyWhen": "changedFiles匹配 **/*.js **/*.ts",
        "description": "修改 JS/TS 文件前检查代码规范"
      }
    ]
  }
}

5. 复合 Hook

组合多个检查步骤:

json
{
  "hooks": {
    "BeforeModify": [
      {
        "name": "Pre-commit checks",
        "command": "npm run pre-commit",
        "description": "运行所有预提交检查"
      }
    ]
  }
}

在 package.json 中定义:

json
{
  "scripts": {
    "pre-commit": "npm run format && npm run lint"
  }
}

6. 数据库迁移 Hook

修改数据库相关文件后提示:

json
{
  "hooks": {
    "AfterModify": [
      {
        "name": "Migration reminder",
        "command": "echo '记得运行数据库迁移!'",
        "runOnlyWhen": "changedFiles匹配 **/migrations/** prisma/schema.prisma",
        "description": "数据库变更后提醒迁移"
      }
    ]
  }
}

下一节: 18 另一个实用 Hook