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 guy that rejects it, but you'll have to! The other dev then needs to incorporate the feedback, you need to review again. That's just 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.

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