lefthook如何与其他工具组合使用?
lefthook 作为一个高性能、跨语言的 Git hooks 管理工具,设计上非常注重组合性(composability)。它本身不提供 linting、formatting、testing 等具体功能,而是通过调用你项目中已有的工具(如 ESLint、Prettier、TypeScript、Vitest、Go vet、Rust clippy 等)来实现自动化。
以下是 lefthook 与其他常用工具组合使用的典型方式和最佳实践:
✅ 1. 与代码格式化/检查工具组合(前端)
示例:ESLint + Prettier
# .lefthook.yml
pre-commit:
parallel: true # 并行执行,更快
commands:
eslint:
glob: "*.{js,ts,jsx,tsx,vue}"
run: npx eslint {staged_files} --fix
prettier:
glob: "*.{js,ts,json,md,yml,yaml,css,scss,vue,html}"
run: npx prettier --write {staged_files}
✅ 技巧:使用
{staged_files}自动传入暂存文件列表,避免全量扫描。
✅ 2. 与类型检查工具组合
示例:TypeScript 类型检查
pre-commit:
commands:
type-check:
glob: "*.{ts,tsx}"
run: npx tsc --noEmit
⚠️ 注意:
tsc --noEmit只做类型检查,不生成文件。
✅ 3. 与测试框架组合
示例:运行单元测试(Vitest / Jest)
pre-push:
commands:
test:
run: npm run test:unit -- --passWithNoTests
✅ 建议:将耗时较长的测试放在
pre-push而非pre-commit,避免阻塞提交。
✅ 4. 与提交信息规范工具组合
示例:commitlint(校验 commit message 格式)
commit-msg:
commands:
commitlint:
run: npx commitlint --edit {1}
📝 需要配合
@commitlint/config-conventional等规则包使用。
✅ 5. 与多语言工具链组合(后端/全栈项目)
示例:Go 项目
pre-commit:
commands:
go-fmt:
glob: "*.go"
run: go fmt {staged_files}
go-vet:
glob: "*.go"
run: go vet ./...
示例:Rust 项目
pre-commit:
commands:
rust-fmt:
glob: "*.rs"
run: cargo fmt -- {staged_files}
clippy:
run: cargo clippy -- -D warnings
✅ 优势:
lefthook无需 Node.js,Go/Rust 开发者可直接使用。
✅ 6. 与 Husky 迁移(替代方案)
如果你之前用 husky + lint-staged,可以完全迁移到 lefthook:
| Husky + lint-staged | → | lefthook |
|---|---|---|
.husky/pre-commit |
→ | .lefthook.yml 中的 pre-commit |
lint-staged 配置 |
→ | commands + glob + {staged_files} |
✅ 7. 高级技巧:复用 npm scripts
你可以直接调用 package.json 中定义的脚本,保持逻辑集中:
// package.json
{
"scripts": {
"lint": "eslint src --ext .ts,.tsx",
"format": "prettier --write src"
}
}
# .lefthook.yml
pre-commit:
commands:
lint:
run: npm run lint
format:
run: npm run format
⚠️ 注意:这种方式会全量运行,而非仅处理 staged 文件。如需过滤,仍建议在
run中直接写命令并使用{staged_files}。
✅ 8. 跳过钩子(临时)
开发时可通过以下方式跳过:
git commit --no-verify # 跳过所有 pre-commit 钩子
🔧 安装与初始化
-
安装 lefthook(推荐全局或项目本地):
# 全局(推荐) npm install -g lefthook # 或 pnpm/bun -
在项目根目录初始化:
lefthook install -
创建
.lefthook.yml并配置(如上所示)。
✅ 总结:lefthook 的组合哲学
- 不重复造轮子:调用你已有的 CLI 工具。
- 按需触发:通过
glob和{staged_files}精准运行。 - 跨语言支持:无论 JS/TS/Go/Rust/Python,只要能命令行调用即可。
- 高性能:Go 编写,毫秒级启动,不影响开发体验。
💡 最佳实践:将
lefthook作为你的 Git 自动化中枢,统一管理所有 pre-commit / pre-push / commit-msg 等任务,替代 Husky + lint-staged + commitlint-cli 的组合,更简洁高效。

浙公网安备 33010602011771号