How to lint Git commit messages


This post goes over how to lint Git commit messages with commitlint and husky (see demo repository).

Prerequisites

Husky

This section goes over how to set up commitlint with the latest husky version.

Watch YouTube video:

Install commitlint with a config:

npm install @commitlint/{cli,config-conventional} --save-dev

This command installs both @commitlint/cli and @commitlint/config-conventional.

config-conventional is a standard based on the Angular convention.

Create .commitlintrc.json, which extends the rules from config-conventional:

touch .commitlintrc.json
{
  "extends": ["@commitlint/config-conventional"]
}

Or export the rules in commitlint.config.js:

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

Install husky:

npm install husky --save-dev

Enable Git hooks:

npx husky install

Or add postinstall script to package.json to enable Git hooks after npm install:

{
  "private": true,
  "scripts": {
    "postinstall": "husky install"
  },
  "devDependencies": {
    "@commitlint/cli": "latest",
    "@commitlint/config-conventional": "latest",
    "husky": "latest"
  }
}

It’s assumed that the package is private. If the package is public, then make sure to disable postinstall script using pinst. See Husky docs for more information.

Add the commit-msg hook:

npx husky add .husky/commit-msg 'npx commitlint --edit $1'

Make sure to use single quotes intead of double quotes so $1 is not escaped.

Test that the commit hook works.

Husky 4

This section goes over how to set up commitlint with husky version 4.

Install commitlint with a config:

npm install @commitlint/{cli,config-conventional} --save-dev

Create .commitlintrc.json, which extends the rules from config-conventional:

touch .commitlintrc.json
{
  "extends": ["@commitlint/config-conventional"]
}

Or export the rules in commitlint.config.js:

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

Install husky@4, which sets up the Git hooks:

npm install husky@4 --save-dev

Create .huskyrc (or .huskyrc.json) and add the Git commit-msg hook that runs commitlint:

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

Or add the hook to package.json:

{
  "devDependencies": {
    "@commitlint/cli": "latest",
    "@commitlint/config-conventional": "latest",
    "husky": "4"
  },
  "husky": {
    "hooks": {
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  }
}

Test that the commit hook works.

Test

Commit and verify the message follows Conventional Commits:

git commit -m 'add commitlint' # fail
git commit -m 'feat: add commitlint' # success


Please support this site and join our Discord!