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.
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
- Install
commitlint
npm i -D @commitlint/{config-conventional,cli}
- 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
- Install
husky
npm i -D husky
- Enable git hooks
npx husky install
- 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
- Install
commitizen
npm i -D commitizen
- Initialize project to use the
cz-conventional-changelog
adapter
npx commitizen init cz-conventional-changelog --save-dev --save-exact
- 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.