Using Git Hooks with npm Scripts
Automating git hooks used to be reserved for dev-ops.
At Hexient Labs, we write React, Angular, and Node sample projects all the time. Our projects are linted and tested- and we feel very strongly that automating those processes is important.
We don’t want ourselves, or our students to be able to commit poorly styled code, or push code that fails tests. Of course you can always make a WIP (work-in-progress) commit, but when you’re writing production-ready applications with automated deploy processes, it’s very important to catch potential errors before they’re released to the world.
Originally published in 2014, Husky has over 20k download/day of npm and is a great way to use existing technologies to use git pre-commit and pre-push hooks. What’s so awesome about Husky in my opinion in the fact that it fits into your normal development workflow. I already use npm scripts to trigger a build of my React app, so in a few steps, I can make sure my code is linted and tested before I ever push it.
Let’s look at an example of using Husky. All we have to do is npm (yarn) install.
yarn add husky --dev
Next, let’s add a few scripts to our package.json.
"precommit": "node_modules/.bin/eslint src",
"start": "node index.js",
Some of this may look familiar. You may already have a “build” and “start” script as seen above; however, what’s new is the “precommit” and “prepush” scripts. These are special names that husky recognizes to run whenever you are trying to do a
git commit or
git push, respectively.
Also note: I’m using the local
eslint sourced from the
node_modules folder. That’s because different projects may use different versions of those dev dependencies. So, when another developer starts working on my code, the dependencies are local, and not dependent on what ever version of
eslint they may use, or have installed on their machine.
Now you may be thinking, what else do I have to do? Answer: nothing. If you’ve ever worked with git hooks before, you should know how amazing that is.
If you want more pro-tips from Hexient Labs, check out our other posts!