In today's tutorial, you will learn about a simple way to add git pre-commit hooks into your Javascript project, using husky. husky is a package that when configured correctly, will enforce that your code runs against a pre-commit check that you can define in your packages.json script whenever your project is run. Unless you are a complete GIT nerd, I'm assuming an introduction on git hooks will help, so we will start there!

Git Hooks Explained

When you create a new repository using git init, in your repository you should see a hidden folder called '.git' (if not it will be hidden and you're stuck - Google it!). If you look in here you will see a folder called hooks. Inside hooks you will find lots of example scripts that you can use to learn how to do all sorts of really cool things. You will notice all the files have the word sample in them by default. All Git hooks are disabled by default.

Creating your own GitHub script is possible, however, it is a bit of a faff. You need to write it using PERL, bash etc... and as you only need to write one once in a blue moon, you will likely need to waste a lot of time simply trying to figure out what you need to do. Most front-end developers are familiar with JavaScript and package.json to configure things. When it comes to Git hooks, an easier approach is to configure hooks within your packages.json rather than writing something custom in a hidden folder. This is where Husky comes in.


Husky allows you to create hooks within your packages.json - like precommit and postcommit - that will get triggered when you do a GIT commit. This approach is much nicer and simpler than writing your own GIT hooks, so I recommend that you check it out and start using it on your project! You can install husky using this command:

In your packages.json, you can then add:

After installing Husky, if you look within you .git -> Hooks folder, you can see that Husky automagically creates its own git hook scripts.  The hooks can be set to run scripts in package.json. You could create a hook that runs the command npm test before someone can commit, All you need to do is decide what your commit workflow looks like, test that it works as expected it to and that's it.  If you combine husky with packages like eslint etc.. you can have something pretty powerful, pretty quickly and with the added bonus of not having to write your own scripts.