Skip to main content

Command Palette

Search for a command to run...

Setting up pre-commit hook with husky to automate code formatting🪝

Updated
2 min read
Setting up pre-commit hook with husky to automate code formatting🪝
S

Hi there! 👋 I am a passionate and dedicated Web Developer with a keen interest in UI/UX design. I have a strong work ethic and am always eager to learn and grow in my field. I am also a technical blogger, sharing insights on web development and more.

If you're looking for a creative and driven developer who is always up for a challenge, I would love to connect with you! 🙌

Intro ✨

I have a React TypeScript project for which I want to automate code formatting before committing changes to the repo, hence in this tutorial, I will teach you to do the same using husky, lint-staged & prettier.

Installing and Setting up Husky 🐶

npx husky-init && npm install

Installing lint-staged and prettier 📦

npm i lint-staged prettier -D

The -D flag makes sure that these packages are installed as dev dependencies in package.json

To automatically have Git hooks enabled after installation, edit package.json

"scripts": {
    ...
    "prepare": "husky install"
}

Setting up prettier with lint-staged in package.json 🚀

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

You can also overwrite/edit the prettier default config by adding the .prettierrc.json config file.

More about it in the docs: https://prettier.io/docs/en/configuration.html

Creating the pre-commit hook 🪝

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

Try to make a commit #️⃣

git commit -m "Keep calm and commit and let the code format itself!"

Conclusion 😉

So, we now finally have the pre-commit hook set up. Now every time you try to commit changes all the staged files with be formatted automatically! Wooohhoo 🥳

You can also try to setup up linting using eslint with the pre-commit hook so that you are committing quality code.

Reference 🔗

https://typicode.github.io/husky/

Happy Coding! 😎