Always write perfect commit messages with Git Commitizen and Husky

git

We’ve all been there, looking at a function and don’t understand a thing of what it does. The next step is of course look at the commit message, the git blame. That will explain everything for us. Or will it?

We open it up and we see this:

Fix an error

What is that? What does it even mean? That is so bad and doesn’t tell us anything.

Fortunately there are tools that will help (or enforce) us to write better commit messages. We will look at two tools in this guide, Git Commitizen and Husky. We won’t install Git Commitizen directly as a dependency but we need some linting rules.

npm install --save-dev @commitlint/cli @commitlint/config-conventional husky

Husky will hook into our git commands and check them with the linting config. Next we need some configuration files in our project root.

Create a .huskyrc used for telling husky to check commit messages.

{
  "hooks": {
    "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
  }
}

Then we need to configure our commit linting with a commitlint.config.js. Here we use the default config-conventional but you can tweak it anyway you like to fit your style.

module.exports = {
  extends: ['@commitlint/config-conventional']
};

Now when we try to write a commit message that isn't valid according to our linting we will get an error, or multiple.

Error when writing invalif commit msg

To help us write valid messages we can type npx git-cz. By using npx we don’t have to install the package as mentioned before, but instead running the script directly.

Pick what kind of commit it is

Help with writing good commit msg

Great! Now we’ll always have perfect commit messages for all team members. Just follow the step-by-step guide and if you want to know in more detail what to type here is a good guide.