Creating Git Hooks Using Husky
Murtuzaali Surti
Posted on October 9, 2022
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.
You can create hooks in the .git/hooks
directory but you can automate the process using husky!
Prerequisites :- nodejs
Installing Husky
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 package.json
file.
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 package.json
,
"scripts": {
"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.
"scripts": {
"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"
Replace npm run format
with the command which will format your code.
You can replace pre-commit
with some other hook such as pre-push
, post-commit
, post-checkout
, etc.
Another example could be, if you want to minify javascript before pushing to production, you can use pre-push
git hook.
npx husky add .husky/pre-push "npm run minjs"
"scripts": {
"minjs": "terser js/app.js --compress --mangle --output js/app.min.js"
}
Find the list of various git hooks on the official git site.
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.
Signing off.
This post was originally published in Syntackle.
Posted on October 9, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.