Beginner's Guide to Using Husky for Git Hooks with a Step-by-Step Example
Husky is a popular tool for managing Git hooks in JavaScript/TypeScript projects. Git hooks are scripts that run automatically when certain Git events occur, such as committing code or pushing to a remote repository.
This tutorial will guide you through setting up Husky in a Node.js project and creating a simple example with a pre-commit hook.
We will test this on a brand new next.js project.
Initialize a new Node.js project:
npx create-next-app@latest husky-tutorial
cd husky-tutorialInstall Husky:
npm install --save-dev huskynpx husky init.husky directory in your project, where Git hooks managed by Husky will reside. It will also create a pre-commit hook as an example. This won't work for next but we will fix that in the next step.pre-commit HookCreate a pre-commit hook:
open the .husky/pre-commit file in your editor and change the contents to the following.
npm run lint
pre-commit HookStage the file for commit:
git add .Attempt to commit:
git commit -m "Test Husky pre-commit hook"The pre-commit hook will run npm run lint, which in turn runs ESLint. If there are linting errors, the commit will be blocked.