How to Setup Git Commit Hooks with Husky in a React App
Conventional commits, ESLint, Prettier and Jest
Git hooks are scripts that run automatically every time a particular event occurs in a Git repository. They let you customize Git’s internal behaviour and trigger customizable actions at key points in the development life cycle.
When I was setting up the Hooks, it was a bit confusing because the library had two options depending on the version. In this article, we will use the latest version (7.0.0).
This article is an attempt to help you set up Git Hooks in a few minutes.
If you want to follow this tutorial, you must have installed and configured:
- React App with TypeScript
- ESLint and Prettier
I have already created a template that you can use: react-template
Let’s do it!
Install Commit lint conventional:
npm i @commitlint/config-conventional --save-dev
Install Commit lint CLI:
npm i @commitlint/cli --save-dev
Create a file in the base of your project:
npm i lint-staged --save-dev
add the lint-staged config in the package.json
“eslint — fix”
“**/*”: “prettier — write — ignore-unknown”
npm install husky --save-dev
package.json > prepare script and run it once:
npx husky-init && npm install
It will setup husky, modify
package.json and create a sample
pre-commit hook that you can edit. By default, it will run
npm test when you commit.
Change the pre-commit file in the /.husky directory, change
npm test to:
Now let's add another hook for commit-msg:
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
And the last one for pre-push:
npx husky add .husky/pre-push 'npx --no-install jest'
Wrapping it up
This is not the only way to setup Git Hooks, but probably the must easier.
I hope you have been able to setup it correctly, if you have any questions you can leave them in the comments.