Stop Wasting Build Minutes
Want to keep your Git history clean, your team happy, and your build minutes down? This guide will help you do just that.
CI pipelines are great. They make sure your code doesn’t break anything and follows conventions. Usually, they run tasks like unit tests, linting, and builds.
But sometimes the pipeline fails over a silly linting error. It did its job—stopping bad code from shipping—but that could’ve been caught earlier on your own machine!
The fix? Automate these checks locally before your PR. That’s where Git hooks come in. This tutorial covers the basics to help you get you and your team started.
Writing git hooks comes with a few challenges, mainly to ensure they are installed on your teammates’ machines.
Husky? 🐶
Husky is a tiny tool that makes it easy to set up git hooks and share them across your team. We will use it together with lint staged.
1. Install husky
npm install -D husky
# or
yarn add -D husky
2. Enable git hooks
npx husky install
3. Automate git hook installation for your teammates
For npm, add this prepare script to your package.json:
{
"prepare": "npx husky install"
}
Yarn requires a slightly different configuration:
{
"private": true,
"scripts": {
"postinstall": "npx husky install"
}
}
Using Yarn2 in a non-private repo? Check this link.
4. Install lint-staged
npm install -D lint-staged
# or
yarn add -D lint-staged
Add the lint-staged configuration to your package.json and customise it to your needs. We assume that you already have linters and tests scripts set up.
"lint-staged": {
"*.{ts,tsx}": [
"npm run format", // prettier --write script
"npm run lint:fix" // eslint --fix script
"npm run test" // jest
]
},
5. Create your hook
This command will create a .husky folder at the root of your project:
npx husky add .husky/pre-commit "npx lint-staged"
What did we achieve?
- Git hooks (via Husky) now run lint checks on each commit.
- Linting only targets staged .ts and .tsx files.
- Auto-fixable errors are fixed and committed; others cause the commit to fail with error details.
- Hooks are automatically installed for teammates through the prepare/postinstall scripts.
Git 2.9+ is required for Husky, as it uses core.hooksPath to point to the .husky folder.
Final thoughts
Git hooks help catch mistakes early, keep your Git history clean, and save build minutes. Just remember, they complement—not replace—CI pipelines. And if needed, you can skip hooks with —no-verify.
Thanks for reading! 😃