Git Hooks
๐ Covered in this chapter:
Pre-Commit Hook ยท Commit-Msg Hook ยท Pre-Push Hook ยท Husky ยท lint-staged
Automate checks โ linting, formatting, tests โ at key points in your Git workflow using Git hooks and tools like Husky.
1Git Hooks โ What You'll Learn
Automate checks โ linting, formatting, tests โ at key points in your Git workflow using Git hooks and tools like Husky.
Here's everything this chapter covers, in the order you'll learn it:
- What Git hooks are
- The pre-commit hook (runs before a commit is created)
- The commit-msg hook (validates commit messages)
- The pre-push hook (runs before pushing)
- Auto-formatting code before commit
- Linting code before push
- Running tests automatically before push
- Husky โ a popular tool for managing hooks in JS projects
- lint-staged โ running linters only on staged files
- Handling and debugging hook failures
2Working Example
๐ป Example: Git Hooks
Terminal
npm install --save-dev husky lint-staged
npx husky init
3Best Practices & Common Pitfalls
๐ก Key things to remember:
- Hooks catch problems (bad formatting, failing tests, broken lint rules) locally, before they ever reach a shared branch or trigger a slower CI pipeline.
โ Frequently Asked Questions (FAQ)
Q What's the most important thing to understand about git hooks?
Focus on: Pre-Commit Hook ยท Commit-Msg Hook ยท Pre-Push Hook ยท Husky ยท lint-staged. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Is git hooks something I'll use often in real projects?
Yes โ every concept in this chapter reflects a real, everyday part of professional Git and GitHub workflows, not just a theoretical exercise.