How to Use Husky for Git Hooks: Simple Setup and Examples
To use
husky for Git hooks, first install it in your project with npm install husky --save-dev. Then enable Git hooks by running npx husky install and add hooks using npx husky add .husky/pre-commit "npm test" to run commands before commits.Syntax
Husky setup and hook commands explained:
npm install husky --save-dev: Adds Husky to your project as a developer tool.npx husky install: Initializes Husky and creates the.huskyfolder for hooks.npx husky add .husky/pre-commit "command": Adds a Git hook script that runscommandbefore a commit.
bash
npm install husky --save-dev
npx husky install
npx husky add .husky/pre-commit "npm test"Example
This example shows how to set up Husky to run tests before every commit to ensure code quality.
bash
npm install husky --save-dev npx husky install npx husky add .husky/pre-commit "npm test" # Now try to commit changes # If tests fail, commit is blocked
Output
husky > Setting up Git hooks
husky > pre-commit hook started
> npm test
> my-project@1.0.0 test
> jest
PASS test/example.test.js
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
husky > pre-commit hook succeeded
Common Pitfalls
Common mistakes when using Husky:
- Not running
npx husky installafter installing Husky, so hooks are not activated. - Adding hooks without executable permissions, causing them not to run.
- Using old Husky v4 syntax instead of the current v8+ commands.
- Forgetting to commit the
.huskyfolder to version control.
bash
## Wrong: Adding hook without install npx husky add .husky/pre-commit "npm test" # This won't work if 'npx husky install' was not run first ## Right: Proper setup npm install husky --save-dev npx husky install npx husky add .husky/pre-commit "npm test" chmod +x .husky/pre-commit
Quick Reference
| Command | Purpose |
|---|---|
| npm install husky --save-dev | Install Husky as a dev dependency |
| npx husky install | Initialize Husky and create .husky folder |
| npx husky add .husky/pre-commit "command" | Add a pre-commit hook to run a command |
| chmod +x .husky/pre-commit | Make hook script executable |
| git add .husky | Add hooks folder to version control |
Key Takeaways
Install Husky and run 'npx husky install' to activate Git hooks.
Add hooks with 'npx husky add' and specify the command to run.
Make hook scripts executable with 'chmod +x' to ensure they run.
Commit the '.husky' folder so hooks work for all team members.
Use Husky hooks to automate checks like tests or linting before commits.