I’ve been trying to setup Husky with Commitizen to add git hooks to my project. I wanted if when anyone does git commit on the project, it should open the Commitizen menu for creating nice commit messages. But seems like recently Husky released its 8 version which has breaking changes, which means most of the online articles using package.json to achieve the above goal are outdated now and won’t work. I did some research and dived into the documentation to see what should be the changes to setup Commitizen for Husky 8. Below given are steps about how I achieved it.
pre-commithook in the
pre-commithook is run before we even write the commit message. It is used to inspect the code before we commit it, lint checks and tests commands can be placed in this file if required.
npx husky-init && npm install
Don’t place your Commitizen command in
pre-commitfile as it will not be able to add the commit message creating empty messages even after input.
npm install -g commitizen commitizen init cz-conventional-changelog --save-dev --save-exact
package.jsonitself but now this is deprecated. To add Commitizen to git hooks we have to create a file in
.huskyfolder with the same name as the git hook we want. For Commitizen we need
prepare-commit-msghook is run before the commit message editor opens but after the default message is created. It lets us edit the default message of our commit giving us the ability to use Commitizen command here. Below is given the Husky command which will create the file and also add the command triggering Commitizen to the same file.
npx husky add .husky/prepare-commit-msg 'exec < /dev/tty && npx cz --hook || true'
That’s all. Try running git commit now and you will see nice input field open up which helps create standard git commit messages.
Made with ❤ at Earth.