Pre-commit hooks with Husky
Introduction
Maintaining high quality code, consistency and tests are essential for any software projects. While multiple people are working on the project, it's common that some unlinted code or failing test will slip through. To address these challenges, Husky provides a powerful automation tool that ensures to run certain checks and tests before anyone can commit.
Pre-commit hooks and Husky
pre-commit hooks are set of commands that run before the commit is finalized. It ensures that predefined rules such as linting, formatting and running tests are all checked before git commit is registered. Husky empowers developers to automate pre-commit checks, enhancing code quality and productivity.
Set Up
I love working with NestJS Framework and I'll be setting up a project from scratch, then we will enable pre-commit hooks for linting and running tests.
We will bootstrap a new project using nestjs CLI command
nest new my-project
It will initialize a new project and sets up a git.
Now, In order to configure Husky, we need to install some new packages as dev dependencies
yarn add -D husky lint-staged eslint eslint-config-prettier
Let’s look at the dependencies and see what they do:
- Husky: It helps you define pre commit and pre push hooks. You can specify any commands you wish to execute before one actually commit on the repository.
- Eslint: Eslint is a great package build to manage rules across the codebase. We can specify the coding practices we wish to be implemented throughout the project.
- Lint-staged: Lint staged helps us do linting before commits when configured with husky. Husky is only there to define which command to run on pre commit. Lint staged will be the actual command for that.
- Eslint-config-prettier: Just existing to override eslint configs so that it doesn’t conflict with prettier.
Initialize husky:
npx husky-init
Update the file .husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
yarn format
yarn lint
yarn test
Now, whenever we run git commit
, all the defined scripts will run before commit finalizes.