I’ve never used it, but I always wanted to, so here we go. I know it’s something that’s done at the beginning, but we’re not that far from it. For the moment, I just want to use Husky for commit lint because I like my commits well defined and not just a few words (or even “--”).
To do so, the first thing to do is install the required dependencies for Husky and Commitlint. We’ll do this by using:
pnpm add -D husky @commitlint/{config-conventional,cli,types}
This is the same as:
pnpm add -D husky @commitlint/config-conventional @commitlint/cli @commitlint/types
Commit lint config file
Now we have to configure Commitlint. We’ll create a commitlint.config.ts
in the root directory and add this content:
import type { UserConfig } from '@commitlint/types';
const Configuration: UserConfig = {
extends: ['@commitlint/config-conventional'],
};
export default Configuration;
I like to use a git naming convention to make my commits readable and understandable for when I have to look for a specific one. If you want more info about it you can check this.
To give you an idea, this is the structure of a commit using the naming convention (you can always customize the structure; it's not a one-size-fits-all rule):
<type>(<scope>): <subject>
Enabling Husky
Next up is enabling Husky in the project. We’ll do this by running the following command:
pnpx husky init
Now we need to add the commit-msg hook using this command:
echo "pnpx commitlint --edit \$1" > .husky/commit-msg
This will run Commitlint on every commit message and block those that don’t follow the rules.
After running this command, we are ready to test if it works.
Testing if it works
We’ll now make a commit for the package.json
to specify that we added Husky.
After running it, we get this pre-commit
error. To solve this (or avoid it), we need to delete the file with the same name inside the .husky folder. Just delete it.
Once done, we can now try again by adding the package.json
and committing with a message that doesn’t follow the convention:
As we can see, it worked.
Now we can enter a correct message to see if it passes.
It worked; Husky is now ready to stop us from committing without following the rules 😜.
In case you were wondering, the abbreviation for the commit message (gcmsg
) is one of many abbreviations configured with oh-my-zsh (you can also customize them) with the git plugin.
That's it for this part.
Salut, Jordi.
Check the repository HERE.