Fail early with Husky pre-commit hooks

Pre-commit hooks are nothing new, it's been around for ages. It allows you to hook into certain git events. The most popular one is definitely the so called pre-commit hook. It runs before your commit is created and it can possibly prevent it even from being created.

Now this is nice isn't it? It's common to have some linters run as a pre-commit hook as they'll prevent you from committing πŸ’© code. Except there's one little issue with those git hooks though. They are not shared by default. Each team member would need to configure the git hooks manually.

Usually this happens by following setup instructions in a README. And this creates another problem: it's not enforced. People might simply forget, read over it, re-clone there repo and skip setup...

And because it's not enforced...

We might end up in the scenario where you're reviewing a PR but CI has failed because somebody didn't follow the rules. And then you don't want to be that dev that rejects it, but you'll have to!

279591e6-ead4-4c98-a956-7deef82c3c05.gif

And when the other dev comes back and sees the feedback a few moments later this usually happens.

7fe60fae-e0a7-4913-9ef4-9ba7ff06a0f6.jpg

Now that's a waste of time & effort and is polluting your git history. If we could only prevent this...

Husky to the rescue πŸš‘

Luckily, for Node/JS projects there's this package Husky. It allows you to configure scripts as git hooks in your package.json and it can enforce this because it installs the commit hooks on postinstall.

So all you really need to do is add Husky to your dev dependencies: yarn add --dev husky.

And add something like the following configuration to your package.json.

"husky": {
  "hooks": {
    "pre-push": "yarn lint"
  }
}

Now I went with pre-push because linting takes a few seconds and I don't like to wait a few seconds every commit I do. But I also don't mind rebasing those commits before I push them to clean them up if there would be issues. The important thing here is: it doesn't let me push πŸ’© code.

df353918-c78f-4c5d-a991-abec2efe33e6.gif

Now get to it and add Husky 🐢 to your project!