Lesson 14 / 27
Pre-commit Hooks & Husky
Block bad commits with Husky and lint-staged so ESLint and Prettier run only on staged files.
Husky workflow
Husky runs ESLint and Prettier before each commit, blocking bad commits. lint-staged runs the tools only on staged files for speed.
Setting up Husky
Install Husky and configure pre-commit hook to lint before commits.
npm install --save-dev husky lint-staged
npx husky init # creates .husky/pre-commit and a prepare script
# .husky/pre-commit
npx lint-staged
# package.json
"lint-staged": {
"*.{js,ts,tsx}": "eslint --fix",
"*.{js,ts,tsx,json,md,css}": "prettier --write"
}
Output:
Husky and lint-staged configured
Skip when necessary
Use git commit --no-verify to bypass hooks in emergencies (e.g., hotfix). But document why and fix it immediately after.
Quick check
Quick check: What does lint-staged do?
- Lints all files in the repo.
- Stages files automatically.
- Installs Node
- Runs linters only on files staged for commit.
Answer
Runs linters only on files staged for commit. — lint-staged improves speed by checking only changed files, not the entire codebase.