Slimmer Code Reviews with Husky
Husky is a simple tool for configuring Git hooks in a project. It really shines when you need to easily configure Git hooks for a project across a team. That is what we are going to do today.
First, we need to add a script to our
package.json file. We already have an existing command for eslint configured (
npm run lint), so all we need to do to get Husky configured is add a
prepush script that runs the lint script.
"lint": "gulp lint",
"prepush": "npm run lint"
Next, we can install husky into our project using the following command.
npm install husky --save-dev
It might seem like we should have done this first but Husky itself works by using an
npm install lifecycle hook that fires after
npm install is run. This means the husky setup we just did will take effect now.
Now you can commit and push these changes. You will see that it runs the linting script before the push runs. If the linting script fails, the push will not happen.
There is another tool called lint-staged that will run a given script only on staged files in Git. This is great if want if you are trying to slowly roll linting into a project and taking things a file at a time. It is not a replacement for Husky. It is really more of an enhancement to Husky. We can go over lint-staged in more detail in a later article.