Have you ever found yourself repeatedly running tests and lint commands before pushing new code? If so, Husky can make your life easier. Husky is an NPM package that helps us to manage Git hooks effortlessly. It enables us to automatically lint commit messages and code, as well as run tests before committing and pushing changes.
1. Installation
Like other NPM packages, we need install Husky before using it:
npm install --save-dev husky
2. Initializing Husky
After installing Husky, we set it up by running the init
command.
npx husky init
This command generates a pre-commit
file inside the ./husky/
directory and adds a “prepare": "husky"
script to the package.json
file.
The pre-commit
file allows us to define commands that should run before committing. If we want to execute commands before pushing changes, we can create a pre-push
file in the same directory.
3. Adding Scripts and Testing
Let’s assume we’re working on a React application and we have already configured testing and linting in our project. For example, in the package.json
file:
{
...
scripts: {
"test": "jest",
"lint": "eslint src"
}
}
If we want to run tests and linting before committing, we can add these scripts to the pre-commit
file as shown below:
npm test
npm run lint
That’s it! We’ve successfully set up a Git hook with husky. From now on, every time we commit changes, tests and linting will run automatically before the commit is finalized
Note that if we want to test our Git hook without committing real changes, we can add exit 1
to the pre-commit
file:
npm test
npm run lint
exit 1
If linting or tests fail, Husky will block the commit. We need to fix the issues before committing again, ensuring code quality.
In conclusion, Husky is a powerfull tool that helps enhance commit quality and streamline workflows. With a lightweight size of just 2KB, it is both efficient and easy to use, making it a popular choice among developers. If you’d like to explore more about husky, you can visit the official documentation here: https://typicode.github.io/husky/