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

Β·

2 min read

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

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

Β