Run npm scripts with git hooks

Elijah Manor
InstructorElijah Manor

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

In this lesson we will look about how we can integrate with git hooks to help enforce a certain level of quality before you either commit your code or push to a remote repository.

[00:01] To help enforce code quality, it's nice to automatically run validation. It'd great if we could make a pre-commit script that would run our npm run lint script. However, that's not supported out of the box. However, there is a handy node package called "Husky" that can integrate Git hooks with npm scripts. Let's install that, npm -i Husky and install it as a dev dependency.

[00:26] Now, if we change one of our files, like utils, and then add some code that will cause a linting error, we'll save that. We'll come back to our terminal and this time, we're going to commit this and say, "Oops, I didn't use that variable," and then Husky will run the pre-commit hook, which will run our linting and you'll see that it failed with an error up here, "Tested, defined, but never used."

[00:53] If we scroll back down, Husky gives us a nice comment letting us know that we could pass the --no-verify flag, if we really needed to commit our code. Let's commit our code again, but this time we'll pass the no verify flag and you'll see it bypassed the whole pre-commit hook and just committed our code.

[01:13] Sometimes linting on every commit can be a little annoying, so another approach that can be handy is to update pre-commit and to make it pre-push instead. I'll save that, we'll go back in our terminal, and now I can commit. Change pre-commit to pre-push and this time it'll commit immediately, but if I go to push this to my origin, the get push commit hook, picks up, runs the linting and fails it for the same reason. I still have the variable that's not being used.

[01:49] Again, if I really wanted to push, I could pass the --no-verify flag and it'll bypass that check.