How to set up Conventional Commits with Commitlint and Husky in may 2022

Kishan Nirghin
2 min readApr 30, 2021
2OCD friendly commit history

This will be a quick setup guide to help you enforce conventional commits using commitlint and Husky.

Without further ado, here are the steps to get it right:

# Step 1. Install commitlint dependency
npm install --save-dev @commitlint/cli
# Step 2. Install conventional commit config
npm install --save-dev @commitlint/config-conventional
# Step 3. Configure commitlint to use conventional commits
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js
# Step 4. Install Husky (v7)
npm install --save-dev husky
# Step 5. Enable Husky
# (NOTE: this will also add a "npm test" pre-commit hook)
npx husky-init && npm install
# Step 5.1 (Optionally) Delete the pre-commit hook
rm .husky/pre-commit
# Step 6. Add commitlint commit-msg hook
cat <<EEE > .husky/commit-msg #!/bin/sh . "\$(dirname "\$0")/_/husky.sh" npx --no -- commitlint --edit "\${1}" EEE

Under the hood

For those who actually want to understand what is happening when running the code above. Here is a brief introduction.

Git supports running scripts on certain events: “hooks”. Husky is a “hook-manager”. Running `npx husky-init` will do 3 things:

  1. RUN > git config core.hooksPath .husky
    This tells git to use the .husky folder to find the scripts to run on each hook.
  2. RUN > npm set-script prepare “husky install”
    This sets the `prepare` script of package.json to `husky install`. The `prepare` script is a special tag with the property that it gets executed automatically when running `npm install`.
  3. Add the .husky/pre-commit file
    This file contains the steps, the code, that will be executed on pre-commit.

To enforce conventional commit styled commit messages a commit-msg hook is required that checks your commit messages against the patterns of conventional commits. Adding the hook in step 6 does exactly that.

Why would I need this?

We all like to kick-start our projects in the best way possible. Personally I like to use a commit-linter as it adds extra structure to a project. Having this added semantic value to commit messages could open up new methods of working; e.g. more reliable search in the commit history.

…That being said enforcing consistency among commit messages usually isn’t the most important task.

BUT. Greatness is in the details my friends.

Source

Commitlint Setup: https://commitlint.js.org/#/guides-local-setup
Husky Setup:
https://typicode.github.io/husky/#/?id=usage

--

--