技能 编程开发 设置代码预提交钩子(Husky)

设置代码预提交钩子(Husky)

v20260426
setup-pre-commit
本指南详细介绍了如何使用Husky、lint-staged和Prettier等工具,为项目设置预提交钩子。它确保了在代码提交前,自动执行代码格式化、类型检查和单元测试,从源头上保证了代码质量和团队协作的规范性。
获取技能
190 次下载
概览

Setup Pre-Commit Hooks

What This Sets Up

  • Husky pre-commit hook
  • lint-staged running Prettier on all staged files
  • Prettier config (if missing)
  • typecheck and test scripts in the pre-commit hook

Steps

1. Detect package manager

Check for package-lock.json (npm), pnpm-lock.yaml (pnpm), yarn.lock (yarn), bun.lockb (bun). Use whichever is present. Default to npm if unclear.

2. Install dependencies

Install as devDependencies:

husky lint-staged prettier

3. Initialize Husky

npx husky init

This creates .husky/ dir and adds prepare: "husky" to package.json.

4. Create .husky/pre-commit

Write this file (no shebang needed for Husky v9+):

npx lint-staged
npm run typecheck
npm run test

Adapt: Replace npm with detected package manager. If repo has no typecheck or test script in package.json, omit those lines and tell the user.

5. Create .lintstagedrc

{
  "*": "prettier --ignore-unknown --write"
}

6. Create .prettierrc (if missing)

Only create if no Prettier config exists. Use these defaults:

{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 80,
  "singleQuote": false,
  "trailingComma": "es5",
  "semi": true,
  "arrowParens": "always"
}

7. Verify

  • .husky/pre-commit exists and is executable
  • .lintstagedrc exists
  • prepare script in package.json is "husky"
  • prettier config exists
  • Run npx lint-staged to verify it works

8. Commit

Stage all changed/created files and commit with message: Add pre-commit hooks (husky + lint-staged + prettier)

This will run through the new pre-commit hooks — a good smoke test that everything works.

Notes

  • Husky v9+ doesn't need shebangs in hook files
  • prettier --ignore-unknown skips files Prettier can't parse (images, etc.)
  • The pre-commit runs lint-staged first (fast, staged-only), then full typecheck and tests
信息
Category 编程开发
Name setup-pre-commit
版本 v20260426
大小 2.21KB
更新时间 2026-04-28
语言