Setting up Pre-Commit Hooks using Husky
Software Engineering is all about automating things. It so happens that every time we commit our changes, we need to remember to check for lint errors. Here is an easy way to get that sorted.
Husky is a project that allows us to run scripts (hooks) before some git commands. The most common one is a pre-commit hook. This basically means a set of commands that can be run before a git commit.
Here is how we set up.
Install Husky —
npm install --save-dev husky
It is a dev dependency because we only need it locally.
Once done, initialise it —
npx husky init
This adds a folder into your root with the name husky
Inside this you will be able to find a file called pre-commit
You can add other files too. But since this is the most used one it appears by default.
Inside this file add the following —
npm run lint
This will run your lint
command inside your package.json
file. Make sure you have that setup. For me, the lint command looks like this —
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
And that is it. From now on, every time you make a commit you will see the linter running and fixing the errors.