Creating Git Hooks Using Husky
Hooks in git are nothing but some code which can be executed at specific points during git execution process.
They are used to verify everything is as expected before or after executing a git command or action. Some common applications include formatting the code before committing, performing build step before pushing the code to production, etc.
Prerequisites :- nodejs
npm install husky --save-dev
Initializing Git Hooks
npx husky install
This will enable you to add git hooks to your project.
One thing to note here is that when collaborating, contributors need to run this command after cloning the project to enable git hooks. But you can bypass this step by adding a
prepare script in your
It will run when you do
npm install in your project so you don't need to perform
npx husky install manually.
To do so, add the following script to
"prepare": "husky install"
But there’s another catch. The
prepare script will also run in production but you need it in production as such, so there are many ways to disable it in production, one of them is by using the
is-ci npm package.
The is-ci package will check if the code is executed in a continuous integration server or not.
npm install is-ci --save-dev
Just change the prepare script to the following.
"prepare": "is-ci || husky install"
Adding Git Hooks
For example, if you want to format your code using a formatting tool before committing the code, you can add git hook to do that using the following command:
npx husky add .husky/pre-commit "npm run format"
npm run format with the command which will format your code.
You can replace
pre-commit with some other hook such as
pre-push git hook.
npx husky add .husky/pre-push "npm run minjs"
Add a script
"minjs": "terser js/app.js --compress --mangle --output js/app.min.js"
You will see a
.husky folder being created in your project and inside it there will be files for all the git hooks which you created.
Make sure to run
git add after you make any changes. Finally, run the git command or action and your git hooks will be executed.
That’s it. For more applications of git hooks, read this article.
Originally published at https://syntackle.live on October 9, 2022.