Writing better commit messages with conventional commits and commitlint

The Conventional Commits help to write well-structured commit messages. It provides an easy set of rules for creating an explicit commit history.

Apr 07, 2022 - 2 min read

What are conventional commits?

The Conventional Commits help to write well-structured commit messages. It provides an easy set of rules for creating an explicit commit history.

<type>[optional scope]: <description>

Examples are

feat: allow provided config object to extend other configs

fix: prevent racing of requests

docs: correct spelling of CHANGELOG

There are other types like build, chore, ci, style, refactor, perf, test

More info on conventional commits

Setting up commitlint on a project

Creating a sample project with Vite

npm create vite@latest
# or
yarn create vite

Install dependencies, if any

npm i

Initialize a git repository, this is important to set up git hooks later.

git init

After creating the project, install commitlint packages

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

Then, add a config file, more info on commitlint configs

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

Now to run commitlint before committing, we need to set up git hook, husky

npx husky-init && npm install
# or
npx husky-init && yarn

Add commit hook

# Add hook
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit $1'
# or
yarn husky add .husky/commit-msg 'yarn commitlint --edit $1'

Now to test commitlint, first stage and commit changes

git add -A

This will fail

git commit -m "foo: this will fail"

⧗   input: foo: this will fail
type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test] [type-enum]

✖   found 1 problems, 0 warnings
ⓘ   Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint

husky - commit-msg hook exited with code 1 (error)

Now try with a valid type

git commit -m "feat: init"

That’s it.

Conventional commits

Commitlint

Husky