Clean and format your code before committing with Husky 🐶

Husky helps to run tests on your code before committing, pushing…

Unsplash: Cody Board

As a developer, you may want to keep your code clean and formatted. If you are coding in JavaScript you might be using ESLint ⚙️

ESLint helps you to format your code by applying custom rules. But if a developer of your team doesn’t lint his code, you will probably have a “dirty” code in your git repo…

…that’s when husky happens to help you.

“Husky can prevent bad git commit, git push and more 🐶 woof!”. It helps you to create simple git hooks. A git hook is a way to run custom scripts when a specific action occurs, example:

  • pre-commit
  • commit-msg
  • post-commit
  • post-merge
  • pre-push
  • And more

Let’s see how Husky will help us 😎

Setup

Husky is a simple npm package, so we can install it very easily:

yarn add -D husky

Here we are installing it as a development dependency.

Once the package installed, you need to edit your package.json file and add these lines (for example):

package.json

These two hooks will run test scripts when committing and pushing to your server.

You can see all the git hooks here.

Usage

There is no special action to do. Your hooks will be triggered when doing the provided actions. Such as:

git commit -m "Trigger pre-commit hook 🤓"

So you can add multiple triggers to run scrips like ESLint…

Husky will help you to run scripts when doing specific actions (e.g: Pre-commit -> lint -> commit; Pre-push -> lint -> Push.)

You can find my other articles and follow me here. Thanks for reading, I hope you learned something new today 🚀

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store