How to Use lint-staged with Husky in Git for Pre-commit Checks
Use
husky to create Git hooks and configure lint-staged in your package.json to run commands on staged files before commit. Install both, add a pre-commit hook with Husky, and define lint-staged tasks to automatically check or fix code only on changed files.Syntax
Husky sets up Git hooks like pre-commit to run scripts before commits. lint-staged runs commands only on files staged for commit.
Typical setup in package.json:
husky: Defines Git hooks and their commands.lint-staged: Maps file patterns to commands to run on those files.
json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.js": ["eslint --fix", "git add"]
}
}Example
This example shows how to install Husky and lint-staged, set up a pre-commit hook, and run ESLint to fix JavaScript files before committing.
bash and json
npm install husky lint-staged --save-dev npx husky install npx husky add .husky/pre-commit "npx lint-staged" # Add this to package.json: { "lint-staged": { "*.js": ["eslint --fix", "git add"] } }
Output
husky > Setting up Git hooks
husky > pre-commit hook created
# When committing, ESLint fixes staged JS files and re-adds them automatically.
Common Pitfalls
- Not running
npx husky installafter installing Husky, so hooks are not created. - Forgetting to add
git addafter fixing files in lint-staged commands, so fixes are not included in the commit. - Using incorrect file patterns in
lint-staged, causing commands to not run on intended files. - Running heavy commands on all files instead of staged files, slowing commits.
json
Wrong: "lint-staged": { "*.js": ["eslint --fix"] } Right: "lint-staged": { "*.js": ["eslint --fix", "git add"] }
Quick Reference
| Command | Purpose |
|---|---|
| npm install husky lint-staged --save-dev | Install Husky and lint-staged as dev dependencies |
| npx husky install | Initialize Husky Git hooks |
| npx husky add .husky/pre-commit "npx lint-staged" | Create pre-commit hook to run lint-staged |
| "lint-staged" config in package.json | Define commands to run on staged files |
| git add | Re-add fixed files to staging after lint-staged fixes |
Key Takeaways
Install and initialize Husky to manage Git hooks.
Configure lint-staged in package.json to run commands on staged files only.
Use Husky's pre-commit hook to trigger lint-staged automatically before commits.
Always include 'git add' after fix commands in lint-staged to update staged files.
Check file patterns carefully to target only intended files.