Git Hooks with Husky

Learn how to set up Git hooks easily with the help of Husky in this lesson.

Git Hooks with Husky

If you followed along , you’ve adopted a cutting-edge development setup completed with integrated linting and auto-formatting. However, your collaborators might not be so prepared. There’s nothing stopping them from submitting a pull request that violates your project’s prescribed ESLint or stylelint rules that will transform when you run it through Prettier. How can you enforce those rules? You could add checks to Travis CI, but then someone still has to fix the problems. Ideally, whoever introduced the problems should fix them before pushing their branch up for everyone else to see.

That’s where Husky comes in. Husky is a tool for managing Git hooks in JavaScript projects. Git hooks are scripts that Git runs before or after certain commands, such as commit or push. In the olden days, developers had to install a project’s Git hooks on their machine manually. Husky makes this much easier. When Husky is installed by npm (or yarn), it uses a post-install script to install its own Git hooks, which will run whatever commands you specify for it in package.json. For developers working on your project, the process is effortless.

Be Considerate with hooks

Git hooks are very powerful, and with great power comes great responsibility. Some project maintainers go overboard with hooks, forcing developers to run big, expensive scripts in the middle of their Git workflow. Respect your collaborators’ time. If it takes more than a few seconds, maybe it should be a CI task rather than a Git hook.

Setting up Husky

The following are the steps to set up Husky:

  • Start by installing the husky package from npm:

    $ npm install --save-dev husky@1.3.1
    + husky@1.3.1
    
  • Then add a new husky section to the project’s package.json to specify the hooks. Start with just one pre-commit hook to run eslint .:

Get hands-on with 1400+ tech skills courses.