Home

Creating a Pre-Commit Hook Using Husky

Medium
Husky

If you have seen repos, mostly from open source with a folder named .husky, you may have wondered what it is.

The general idea of using Husky is to have a pre-commit hook. A pre-commit, as named, is similar to a middleware: before committing to GitHub, it runs some function (mostly formatting).

It is useful when many developers are using the same repo and we want to keep consistency (clean).

Let's create one using Husky and Prettier.

1. Install Husky

npx husky-init && npm install

(Make sure you are in a bash CLI.)

2. Install Prettier

npm i lint-staged prettier -D

3. Add lint-staged to your package.json

"lint-staged": {
  "*.{json,md,html}": [
    "npx prettier --write"
  ],
  "*.{css}": [
    "npx prettier --write"
  ],
  "*.{js,jsx,tsx,ts}": [
    "npx prettier --write"
  ]
},

Only files with these extensions will be affected.

4. Add the hook

npx husky add .husky/pre-commit "npx lint-staged"

This will create the lint command in your pre-commit.

Thennnn done!!!

Bonus: create your own rules

Create .prettierrc.json at the root:

{
  "tabWidth": 4,
  "singleQuote": true
}

Now you can commit your codebase and lint-staged will happen, formatting all your code.