Setting up pre-commit hook with husky to automate code formattingπͺ
Table of contents
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! π
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! π