Linting Git Commits According to the Conventional Commits Specification with Husky and Commitlint
Scenario
Within our Node.js based ( Angular, React, etc.) projects we want to reject commits that do not adhere to the Conventional Commits specification.
Approach
Within our project install commitlint.
npm i -D @commitlint/cli @commitlint/config-conventional
Extend the commitlint conventional configuration.
echo "module.exports = { extends: ['@commitlint/config-conventional'] };" > commitlint.config.js
Install and initialize Husky.
npm i -D husky && npx husky init
In order to trigger commitlint when commits are made, create the commit-msg
file in the .husky
project folder.
echo "npx --no -- commitlint --edit \$1" > .husky/commit-msg
When we run npx husky init
Husky also create the ./husky/pre-commit
file and it contain npm test
and this will cause errors if there is no such script. So replace npm test
with our test command or just delete the pre-commit
file. You can always add it back later.
Assuming we have both pre-commit
and commit-msg
files, set the file permission to executable.
chmod u+x .husky/pre-commmit
chmod u+x .husky/commit-msg
Now try a commit.
touch testfile
add .
commit -m "fooboo: this commit will fail"
We get this linting error.
⧗ input: fooboo: this commit 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 script failed (code 1)
Lets try it again.
git commit -m "chore: commit initial project files"
The files are committed.