Setting up pre-commit hook with husky to automate code formattingπŸͺ

Sridhar MaskeriSridhar Maskeri
2 min read

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! 😎

0
Subscribe to my newsletter

Read articles from Sridhar Maskeri directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sridhar Maskeri
Sridhar Maskeri

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! πŸ™Œ