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

Watch YouTube video:

Install commitlint with a config:

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

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:

{
  "extends": ["@commitlint/config-conventional"]
}

Or export the rules in commitlint.config.js:

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

Install husky:

$ npm install husky

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": "^11.0.0",
    "@commitlint/config-conventional": "^11.0.0",
    "husky": "^5.0.9"
  }
}

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 added correctly.

Test that the commit hook works.

Husky 4

Install commitlint with a config:

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

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

{
  "extends": ["@commitlint/config-conventional"]
}

Or export the rules in commitlint.config.js:

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

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

$ npm install husky@4

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!