Inconsistent code formatting makes code review difficult. When each developer uses a different style, every pull request ends up filled with formatting changes that reduce the readability of the actual code modifications.
Whether you're working solo or on a team, life’s too short to argue about The One True Brace Style or the eternal tabs vs spaces debate.
Tools like ESLint and Prettier solve this by automatically enforcing a consistent style guide. You can run Prettier manually via the command line or have it auto-format on save in your editor. However, this setup relies on each developer having their tools configured properly and it’s easy for that configuration to be missed, misconfigured, or simply forgotten.
Ideally, we want to ensure Prettier and ESLint run automatically after code changes are made but before they're committed to the repository.
Fortunately, Git gives us hooks, which are scripts that run on specific Git events. The pre-commit hook runs right before a commit is finalized the perfect time to apply formatting and lint checks.
You can configure Git hooks manually, but it’s easier and more maintainable to use a tool like Husky to manage them.
One common complaint is that running pre-commit processes like linting, formatting, and tests can be slow especially on larger codebases or lower-end machines. Running Prettier across every file on every commit might be fine for small projects, but it quickly becomes a bottleneck.
That’s where pretty-quick comes in: it runs Prettier only on staged files, keeping commit times fast while still ensuring code consistency.
- A project using npm
- Git installed
- ESLint and Prettier installed and configured
Install husky and pretty-quick:
npm add -D husky pretty-quickHusky v8+ requires manual initialization. Run:
npm exec husky initThis creates a .husky folder and sets up Git hook support for your project.
Add a pre-commit hook with Husky:
npx husky add .husky/pre-commit "npm exec pretty-quick --staged"This hook will:
- Format only the staged files using
pretty-quick
If you'd also like to run your tests before allowing the commit, you can modify the hook:
npx husky add .husky/pre-commit "npm exec pretty-quick --staged && npm test"Make a small code change, stage it, and try committing:
git commit -m "Test Husky hook"If Prettier fails or your tests break, the commit will be blocked until the issues are resolved — keeping your repository clean and consistent.
you want to automatically set up Husky after npm install, you can add a prepare script in your package.json:
"scripts": {
"prepare": "husky"
}This script ensures that Husky installs its Git hooks whenever someone installs your dependencies (e.g. after npm install or pnpm install), which is especially useful for onboarding team members or in CI environments.