DEV Community

Cover image for Husky with commitlint and lint-staged
Edson Junior de Andrade
Edson Junior de Andrade

Posted on • Updated on

Husky with commitlint and lint-staged

In this post, I'll show you how to improve your husky workflow, using pre-commit to trigger error checking on your code before uploading it to the repository.

Start husky with the following command:

npx husky-init
Enter fullscreen mode Exit fullscreen mode

Verify that the husky information has been entered into your package.json:

{

  "scripts": {
    ...
    "prepare": "husky install"
  },
  "devDependencies": {
    ...
    "husky": "^6.0.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

Install husky in your project:

#yarn 
yarn; npx husky add .husky/commit-msg 'npx --no-install commitlint --edit ""'

#npm 
npm install; npx husky add .husky/commit-msg 'npx --no-install commitlint --edit ""'
Enter fullscreen mode Exit fullscreen mode

Checking .husky/commit-msg file you might find the following bash script:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx --no-install commitlint --edit ""
Enter fullscreen mode Exit fullscreen mode

Let's add the commit-lint package to the lint confirmation messages:

#yarn 
yarn add @commitlint/config-conventional @commitlint/cli --dev

#npm 
npm install @commitlint/config-conventional @commitlint/cli --dev
Enter fullscreen mode Exit fullscreen mode

Create the commitlint.config.js file in the root of your directory and insert the following contents:

module.exports = { extends: ['@commitlint/config-conventional'] };
Enter fullscreen mode Exit fullscreen mode

Now we will install lint-staged:

#yarn 
yarn add lint-staged --dev

#npm 
npm install lint-staged --save-dev
Enter fullscreen mode Exit fullscreen mode

In package.json insert the following script for running lint-staged into our project:

 {
   "scripts": {
     ...
     "pre-commit": "lint-staged",
     "prepare": "husky install"
   }
}
Enter fullscreen mode Exit fullscreen mode

We will create the .lintstagedrc file to run eslint and prettier at commit time:

{
  "src/**/*.+(js|json|ts|tsx)": ["eslint"],
  "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": ["eslint --fix", "prettier --write"]
}
Enter fullscreen mode Exit fullscreen mode

Inside .husky/pre-commit insert the following script:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

yarn run pre-commit
Enter fullscreen mode Exit fullscreen mode

Finally, run the command that created the 'prepare-commit-msg' file:

#yarn
npx husky add .husky/prepare-commit-msg 'exec < /dev/tty && node_modules/.bin/cz --hook || true'; yarn

#npm
npx husky add .husky/prepare-commit-msg 'exec < /dev/tty && node_modules/.bin/cz --hook || true'; npm install
Enter fullscreen mode Exit fullscreen mode

That's it! Now test everything we have installed.

Top comments (0)