Git & Version Controlintermediate
Set up pre-commit, pre-push, and commit-msg hooks
Git Hooks Setup
Set up pre-commit, pre-push, and commit-msg hooks
Set up pre-commit, pre-push, and commit-msg git hooks.
Instructions
- Install Husky:
npm install -D husky lint-staged
npx husky init
- Set up pre-commit hook (lint + format staged files):
echo "npx lint-staged" > .husky/pre-commit
- Configure lint-staged in package.json:
{
"lint-staged": {
"*.{ts,tsx}": ["eslint --fix", "prettier --write"],
"*.{json,md,css}": ["prettier --write"]
}
}
- Set up commit-msg hook (enforce conventional commits):
npm install -D @commitlint/cli @commitlint/config-conventional
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg
echo "module.exports = { extends: ['@commitlint/config-conventional'] }" > commitlint.config.js
- Set up pre-push hook (run tests before pushing):
echo "npm test" > .husky/pre-push
Verify
git add . && git commit -m "test: invalid commit" # should fail
git commit -m "test: add hook validation" # should pass