0
0
GitHow-ToBeginner · 3 min read

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 .husky folder for hooks.
  • npx husky add .husky/pre-commit "command": Adds a Git hook script that runs command before 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 install after 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 .husky folder 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

CommandPurpose
npm install husky --save-devInstall Husky as a dev dependency
npx husky installInitialize 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-commitMake hook script executable
git add .huskyAdd 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.