跳转至

本文件使用 Web 特有的钩子建议扩展 common/hooks.md。

Web 钩子

优先使用项目本地工具。不要将钩子连接到远程一次性包执行。

保存时格式化

编辑后使用项目现有的格式化器入口点:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "pnpm prettier --write \"$FILE_PATH\"",
        "description": "Format edited frontend files"
      }
    ]
  }
}

使用 yarn prettier 或 npm exec prettier -- 的等效本地命令也可以,只要使用仓库拥有的依赖关系即可。

Lint 检查

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "pnpm eslint --fix \"$FILE_PATH\"",
        "description": "Run ESLint on edited frontend files"
      }
    ]
  }
}

类型检查

使用 --incremental 在重新运行时复用之前的 .tsbuildinfo(对于未更改的代码,只需 1-3 秒而不是 30-60 秒)。用 timeout 包装,以便挂起的 tsc 能被操作系统回收——这样可以防止当编辑发生得比 tsc 完成更快时出现多进程累积。

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "timeout 60 pnpm tsc --noEmit --pretty false --incremental --tsBuildInfoFile node_modules/.cache/tsc-hook.tsbuildinfo",
        "description": "Type-check after frontend edits (incremental + timeout-capped)"
      }
    ]
  }
}

两个标志都很重要的原因: - 没有 --incremental 时,每次编辑都会从零开始重新检查整个程序。在实际的 Next.js 项目中,这会迅速累积:每 5-10 秒一次编辑 + 30-60 秒的 tsc 运行 = N 个并行 tsc 进程。 - 没有 timeout 时,挂起的 tsc(由于传递依赖项更改、类型检查器在递归类型上停止)不会终止,并在父 shell 退出时成为孤儿进程。 - 需要 --tsBuildInfoFile,因为 --noEmit 通常会抑制 buildinfo 的写入。显式指定路径可让增量继续工作。

在 Windows 上没有 GNU coreutils 时,将 timeout 60 替换为 PowerShell 包装器,或依赖 Stop/SessionEnd 钩子清理停滞的 tsc 进程。

CSS Lint

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "pnpm stylelint --fix \"$FILE_PATH\"",
        "description": "Lint edited stylesheets"
      }
    ]
  }
}

PreToolUse 钩子

文件大小保护

阻止来自工具输入内容的巨大写入,而不是来自可能尚不存在的文件:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write",
        "command": "node -e \"let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{const i=JSON.parse(d);const c=i.tool_input?.content||'';const lines=c.split('\\n').length;if(lines>800){console.error('[Hook] BLOCKED: File exceeds 800 lines ('+lines+' lines)');console.error('[Hook] Split into smaller modules');process.exit(2)}console.log(d)})\"",
        "description": "Block writes that exceed 800 lines"
      }
    ]
  }
}

Stop 钩子

最终构建验证

{
  "hooks": {
    "Stop": [
      {
        "command": "pnpm build",
        "description": "Verify the production build at session end"
      }
    ]
  }
}

顺序

推荐顺序: 1. 格式化 2. Lint 3. 类型检查 4. 构建验证

本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 ev/ECC