Pre-Commit hooks! (e.g prettier)
Setup pre-commit hook for an existing project, we will be using prettier as an example today.
What is a pre-commit hook?
A Pre-commit hook is run just before a commit is added to a new revision. They are mainly used to point out issues in code such as a missing semicolon, formatting, trailing white spaces and debug statements.
In other words, they make your life so much better as a developer.
What is prettier?
Prettier is an opinionated code formatter. If you never want to worry about code formatting again, install Prettier and it will take care of formatting for you.
Setup:
To set up pre-commit we will be using husky — “Git hooks made easy”.
yarn add huskyornpm install husky
The hooks can be set up in your package.json
file and in our case today will be used to run prettier 😁
// package.json
{
"husky": {
"hooks": {
"pre-commit": "npm test",
"pre-push": "npm test",
"...": "..."
}
}
}
Prettifying your code with prettier
Setup:
Installation:
yarn add --dev prettier pretty-quickornpm install --save-dev prettier pretty-quick
Usage:
Using pretty-quick for manual formatting:
with yarn:
yarn pretty-quickorwith npm:
npx -p prettier@latest -p pretty-quick pretty-quick
Automating pretty-quick on pre-commit:
// package.json{
"scripts": {
"pretty-quick": "pretty-quick"
}"husky": {
"hooks": {
"pre-commit": "yarn pretty-quick --staged && git add ."
}
}
}
The additional--staged
means we only look at staged files that are ready to push to our repo (i.e changed files). While the git add .
means we are re-adding the files that are formatted.
Demo:
If you do any git commit now you will see something similar to the screenshot below:
You have successfully learned how to use pre-commit hooks and prettier to format your code on git commit.
Note:
I will recommend setting your own prettier rule on how you want your code to be formatted by adding .prettierrc
file in your project root folder or prettier will use its default:
// .prettierrc{"semi": true,"tabWidth": 2,"trailingComma": "all","singleQuote": false}
Conclusion:
This will make development easier and also make you and your team stick to the same formatting rules. I hope this has been able to help you get started with using Git hooks in your projects.
Thank you for reading.