Git hooks with husky & commitlint

Git hooks with husky & commitlint

Now that we are using lerna to determine package versions, we need to ensure that all commits follow the proper syntax. We can utilize Husky to add a git hook to the commit command. Head over to your command-line interface, make sure you navigate to the root of the project’s monorepo and install husky as a development dependency as follows:

npm install husky --save-dev

Next, you also need to install commitlint to lint commits:

npm install @commitlint/cli --save-dev
npm install @commitlint/config-conventional --save-dev

Next, enable Git hooks using the following command:

npx husky install

Then, add the commit-msg hook using the following command:

npx husky add .husky/commit-msg 'npx commitlint --edit $1'

Next, create the .commitlintrc.json file and add the following configuration:

{
  "extends": ["@commitlint/config-conventional"]
}

Then, create the commitlint.config.js file and the add:

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

Finally, add a Git commit that doesn’t follow the convention:

git commit -a -m "Set up Husky and commitlint"

The operation should be failed with the following message:

⧗   input: Add 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)

If you run the following commit instead it should work:

git commit -m 'feat: set up husky and commitlint'

Conclusion

We can enhance the releasing process by combining lerna with a few additional utilities and conventions. Thanks to using git hooks with husky and commitlint to ensure that all commits follow the proper syntax.


  • Date: