How to configure Husky with Conventional commits?
In this post I will show how you could have a good workflow using husky
Husky is a tool that allows us to execute Git Hooks in a simple way to guarantee that the tests are executed in our code, and to verify that it does not send bugs or inconsistencies to the project repository.
Before configuring Husky, I will first teach how to install and configure Prettier and ESLint
How to configure Prettier #
For this it is very simple, you just have to execute this command:
npm install --save-dev --save-exact prettier
Then we must create a file for the prettier configuration, for faster you can execute this command echo {}> .prettierrc.json
Once that file is created, you must place the configuration, this is the configuration that I use for my projects in javascript
{
"printWidth": 80,
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "all",
"endOfLine": "self"
}
To run prettier you must run this command
Now format all the files with Prettier:
npx prettier --write .
If you want to see the problems, without modifying the files, use:
npx prettier --check .
How to configure ESLint #
It is very easy, since ESLint has a very intuitive way to configure itself by executing this command
npm init @eslint/config
after executing it
This will check all files
npx eslint .
Then what I do is add some commands in the package.json
in the script
section
"format": "prettier --ignore-path .gitignore --write . && eslint --ignore-path .gitignore --fix .",
"lint": "prettier --ignore-path .gitignore --check . && eslint --ignore-path .gitignore ."
It would stay like this. Now we go with Husky
Configure Husky #
Once here you will have to have Git installed and an initialized project.
We are going to install Git, for this you have to execute this command.
npx husky-init
That command will install and configure husky, once that is done you have to edit the command that it will execute before committing, for this you have to go to the .husky
folder to the pre-commit file, there you will have to replace npm test, with the command desired in my case I use the command that we configured earlier, npm run check
we would already have git configured, now comes conventional commits.
Installing conventional commits #
We have to execute this command
npm install @commitlint/{cli,config-conventional} --save-dev
To install commitlint
Then create a file .commitlintrc.json for more speed execute touch .commitlintrc.json
so that it is created and then in its content place
{
"extends": ["@commitlint/config-conventional"]
}
to set it up
Then we add the new configuration. For this we execute this command
npx husky add .husky/commit-msg 'npx commitlint --edit $1'
And it would be.
To test it, trying to make a commit with the message "test" would give an error since it does not follow the rules of conventionalcommits