What is Commitlint? Why to use? How to Setup and more

Trishan Wagle
3 min readSep 7, 2023

--

What is Commitlint?
Commitlint is a simple tool that lints your commit messages and makes sure they follow a set of rules. It runs as a husky pre-commit hook, that is, it runs before the code is committed and blocks the commit in case it fails the lint checks.

Why Commitlint?
Commit Conventions — It makes our commit cleaner, and more specific of what changes we made
Better understanding of commits — A commit with a specific type and scope will help you understand what code the commit changes
Adherence to a particular convention — When you have a big project and a lot of people committing to it, people might forget to use the convention. commitlint blocks such commits so that the commits adhere to the defined convention.

How to setup Commitlint in your project:
Step 1: Install Commitlint
```
# Install and configure if needed
npm install — save-dev @commitlint/{cli,config-conventional}
# For Windows:
npm install — save-dev @commitlint/config-conventional @commitlint/cli
# Configure commitlint to use conventional config
echo “module.exports = { extends: [‘@commitlint/config-conventional’] };” > commitlint.config.js
```

Step 2: Install Husky
Husky improves your commits and more 🐶 woof! You can use it to lint your commit messages, run tests, lint code, etc… when you commit or push. Husky supports all Git hooks, so to use commit lint we need to install and activate Husky in our project. To do so:
```
# Install Husky
npm install husky — save-dev

# Activate hooks
npx husky install
```

Step 3: Add Hook
```
npx husky add .husky/commit-msg ‘npx — no — commitlint — edit ${1}’
```

Done!, Now you can modify commitlint.config.js file and write your own set of rules like, must add feat: or fix: at head of commit message, and more. If commit rules are not followed then the developer will get an error and will not be able to commit. For eg:

I am getting error, because I didn’t add feat: or whatever we have defined in our rule, so now to commit we must use feat, fix, or others that we add in our rules in our commit message, for eg: git commit -m “feat: this is good commit”

Here is my Personal Favourite Set of Rules, you can paste it to your commitlint.config.js file and enjoy using commitlint:

module.exports = {
rules: {
"type-enum": [
2,
"always",
[
"feat","fix", "wip", "build", "refactor"
],
],
"type-case": [
2,
"always",
"lower-case"
],
"type-empty": [
2,
"never"
],
"type-max-length": [
2,
"always",
8
],
"scope-case": [
2,
"always",
"lower-case"
],
"subject-case": [
2,
"always",
"lower-case"
],
"subject-empty": [
2,
"never"
],
"subject-max-length": [2,
"always",
60
],
},
};

Thank You, Everyone!
#happy_learning

My Github: https://github.com/trishan9
My LinkedIn: https://www.linkedin.com/in/trishan9/
- Trishan Wagle

--

--

Responses (1)