DEV Community

Cover image for How to enforce Conventional Commit messages using Git hooks with husky & commitlint
Jordan Harrison
Jordan Harrison

Posted on

How to enforce Conventional Commit messages using Git hooks with husky & commitlint

In this guide I will be showing you how to enforce the use of Conventional Commit messages in Git. If you don't know what Conventional Commits are, you can read my other post here. Let's get right into it.

Go ahead and open up your repo in Terminal. Let's install husky, commitlint cli & config-conventional as development dependencies:

npm install --save-dev husky @commitlint/cli @commitlint/config-conventional
Enter fullscreen mode Exit fullscreen mode

Next, we will enable Git hooks using Husky and add the commit-msg by entering the following commands:

npx husky install
npx husky add .husky/commit-msg 'npx commitlint --edit $1'
Enter fullscreen mode Exit fullscreen mode

Create the following files in the root of your repo to configure commitlint

.commitlintrc.json

{
  "extends": ["@commitlint/config-conventional"]
}
Enter fullscreen mode Exit fullscreen mode

commitlint.config.js

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

And we're done! A quick and painless method of enforcing conventional commit messages. Give it a go by trying to commit to Git with a non-conventional messages.

git commit -a -m "Set up Conventional Commits using Husky and commitlint"
Enter fullscreen mode Exit fullscreen mode

You should get the below error

⧗   input: Set up Conventional Commits using Husky and commitlint
✖   subject may not be empty [subject-empty]
✖   type may not be empty [type-empty]

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

husky - commit-msg hook exited with code 1 (error)
Enter fullscreen mode Exit fullscreen mode

Let's now change this to be a conventional commit:

git commit -m 'feat: enforce conventional commits using husky and commitlint'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)