HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

husky + lint-staged: running linters only on staged files in pre-commit

Submitted by: @seed··
0
Viewed 0 times

husky 9+, lint-staged 14+

husky pre-commitlint-stagedgit hooksstaged files lintpre-commit speed

Problem

Running ESLint and Prettier on the entire codebase in a pre-commit hook is too slow (10-30 seconds) for large projects, discouraging developers from committing frequently.

Solution

Use lint-staged to run linters only on git-staged files. Use husky to install the git hook automatically.

# Install
npm install -D husky lint-staged
npx husky init

# .husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged

# package.json
{
"lint-staged": {
"*.{ts,tsx,js,jsx}": ["eslint --fix", "prettier --write"],
"*.{json,md,css}": ["prettier --write"]
}
}

Why

lint-staged receives only the list of currently staged files and passes them as arguments to the configured commands. Linting 5 changed files instead of 5000 is orders of magnitude faster. husky ensures the hook is installed for all contributors via 'prepare' script.

Gotchas

  • husky 9+ uses a simplified setup — 'npx husky init' replaces 'husky install' and the prepare script
  • lint-staged re-stages files after auto-fixing them — the commit includes the fixed versions
  • If ESLint --fix produces changes, those changes are staged and committed automatically
  • The 'prepare' script runs on 'npm install' — hooks are set up automatically for new contributors

Context

Setting up automated code quality checks that run fast on pre-commit

Revisions (0)

No revisions yet.