Conventional Commits for JavaScript projects

Conventional commits are a great way to standardize the format of commit messages. Thanks to this, it's easy to generate a changelog or the next SemVer automatically.

Conventional commits

The Conventional Commits specification is a lightweight convention on top of commit messages. It provides an easy set of rules for creating an explicit commit history; which makes it easier to write automated tools on top of. This convention dovetails with SemVer, by describing the features, fixes, and breaking changes made in commit messages.

Read more on the official website.

Commitlint _

Commitlint is a tool to check if commit messages are in the correct format.

GitHub: https://github.com/conventional-changelog/commitlint

  1. Install commitlint
npm i -D @commitlint/{config-conventional,cli}
  1. Create commitlint configuration file
echo "module.exports = {extends: ['@commitlint/config-conventional']};" > commitlint.config.js

Husky _

Husky allows us to run git hooks. We will use it to run commitlint and commitizen.

GitHub: https://github.com/typicode/husky

  1. Install husky
npm i -D [email protected]
  1. Enable git hooks
npx husky install
  1. Add a hook to validate commit messages (commitlint)
npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"

Commitizen _

Commitizen makes it easier to create the correct commit message format. When you type git commit, you will be prompted to fill in any required information.

Github: https://github.com/commitizen/cz-cli

  1. Install commitizen
npm i -D commitizen
  1. Initialize project to use the cz-conventional-changelog adapter
npx commitizen init cz-conventional-changelog --save-dev --save-exact
  1. Add a hook to run commitizen before commit
npx husky add .husky/prepare-commit-msg "exec < /dev/tty && npx cz --hook || true"

Add files to the git repository _

You can add .husky, commitlint.config.js and modified package.json to your repository so everyone can use conventional commits right after pulling the changes.

What's next? _

It would be nice to generate changelog and SemVer automatically. I will describe how to do it in the next article.