Skip to main content

Husky, Commitlint, and Prettier Configuration

Configuration to check commit message, and run prettier pre-commit

100 views

In this configuration there are 2 things that will be checked

  1. Checking the commit message following the conventional commits, it will fail to commit if the commit message is not following the rule.
  2. Writing prettier changes before each commit. This is done to prevent developers that did not have prettier installed in their machine.

1. Initialize Husky

npx husky-init && yarn
bash

It will initialize all of the needed files including a sample pre-commit hook.

2. Add Commitlint

FIrst, install the dev dependencies

yarn add -D @commitlint/config-conventional @commitlint/cli
bash

Then, add this to the husky hook

npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
bash

Create commitlint.config.js, you don't need to override the rules if you don't want to

module.exports = { extends: ['@commitlint/config-conventional'], rules: { // TODO Add Scope Enum Here // 'scope-enum': [2, 'always', ['yourscope', 'yourscope']], 'type-enum': [ 2, 'always', [ 'feat', 'fix', 'docs', 'chore', 'style', 'refactor', 'ci', 'test', 'revert', 'perf', 'vercel', ], ], }, };
js

Commit message will be checked before commit now. 🚀

3. Add Lint Staged & Prettier

Install dependencies

yarn add -D lint-staged prettier
bash

Lint staged is used so prettier will not need to check all of the files, but only the staged files.

Add this to package.json

{ // ...existing code, you can split the html,css,json if you add eslint to configuration "lint-staged": { "**/*.{js,jsx,ts,tsx,html,css,json}": ["yarn prettier --write"] } }
json

Then add this to .husky/pre-commit

#!/bin/sh . "$(dirname "$0")/_/husky.sh" yarn lint-staged
bash

You can also add test command here if you want to do test before each commit

4. Add postmerge hook

Use this to add hook, so husky will run yarn everytime we pull changes.

npx husky add .husky/post-merge 'yarn'
bash