Sub topic 14
Checking Staged Files with Husky and lint-staged
This chapter assumes you already have the lint and format npm scripts from the previous chapter, a working ESLint flat config, and Prettier installed. You should also be comfortable with git add, git commit, and the idea of a staging area.
The npm scripts check the whole project when someone remembers to run them. A pre-commit hook runs the checks every time, before the commit exists. It also limits the work to the files being committed, so a large repository doesn't need a full lint on every commit.
What Each Tool Does
Git can already run a script before a commit, but it looks for that script in .git/hooks, which is not version-controlled. Two tools close that gap:
| Tool | Responsibility |
|---|---|
| Husky | Points Git at a committed `.husky/` folder so every clone shares the same hooks |
| lint-staged | Finds the staged files, runs your commands on them, and adds any fixes back to the commit |
Husky decides when something runs. lint-staged decides what runs and which files it runs on. Neither one lints anything itself. They call ESLint and Prettier.
Installing and Wiring the Hook
npm install --save-dev husky lint-staged
npx husky init
echo "npx lint-staged" > .husky/pre-commitnpx husky init does two things. It creates .husky/pre-commit, which contains npm test by default, and it adds a prepare script to package.json:
{
"scripts": {
"prepare": "husky"
}
}npm runs prepare automatically after npm install. That is how a teammate who clones the repository gets the hook without any manual step: running husky sets Git's core.hooksPath to .husky/_. The echo line then replaces the default npm test with npx lint-staged.
In Husky v9, hook files are plain shell scripts. They need no shebang line and no husky.sh sourcing line. If you copy hook files from an older tutorial that includes those lines, Husky v9 prints a deprecation warning.
Configuring lint-staged
Add the configuration to package.json, next to the scripts:
{
"scripts": {
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier . --write",
"format:check": "prettier . --check"
},
"lint-staged": {
"*.{js,mjs,cjs}": ["eslint --fix", "prettier --write"],
"*.{json,md,css}": "prettier --write"
}
}Each key is a glob, and each value is a command or a list of commands. lint-staged appends the matching staged file paths to the end of each command. For example, if you stage src/app.js and README.md, it runs roughly:
eslint --fix /repo/src/app.js
prettier --write /repo/src/app.js
prettier --write /repo/README.mdThe npm scripts are not called here. A script like eslint . already includes a path, and lint-staged would append more paths after the ., so the whole project would be linted anyway.
How the globs match
A glob without a /, such as *.js, matches the file name in any directory, so src/deep/util.js matches. A glob that contains a /, such as src/**/*.js, matches against the path relative to the repository root. Each file is tested against every glob. A file that matches two keys runs both sets of commands, so avoid overlapping globs that both write to the same file.
Order and concurrency
Commands inside one array run in order. Running eslint --fix before prettier --write matters, because Prettier should get the last word on formatting. Separate glob keys run in parallel by default. That is safe only when no file matches more than one key.
What Happens During a Commit
The hiding step is what makes lint-staged safe with partially staged files. Suppose you staged one hunk of app.js with git add -p and left another hunk unstaged. lint-staged temporarily removes the unstaged hunk, so the tools see exactly the content that will be committed. Afterward it puts the unstaged hunk back.
The exit code is the only signal. ESLint exits with 1 when it reports errors and 0 when it reports only warnings. Prettier with --write exits with 0 unless it fails to parse a file.
Making the Hook Stricter or Quieter
The basic config lets warnings through and can print noise. These flags help:
{
"lint-staged": {
"*.{js,mjs,cjs}": [
"eslint --fix --max-warnings=0 --no-warn-ignored",
"prettier --write --ignore-unknown"
],
"*.{json,md,css}": "prettier --write --ignore-unknown"
}
}| Flag | Effect |
|---|---|
| `--max-warnings=0` | ESLint exits non-zero if any warning remains, so warnings also block the commit |
| `--no-warn-ignored` | Suppresses the "File ignored because of a matching ignore pattern" warning when a staged file is listed in your flat config's `ignores` |
| `--ignore-unknown` | Prettier skips file types it cannot parse instead of failing |
--no-warn-ignored matters more than it looks. lint-staged passes file paths explicitly, and ESLint warns about any explicitly passed file that your config ignores. Combined with --max-warnings=0, that warning would block commits of files you deliberately excluded.
Using a JavaScript config for more control
When a command needs different arguments, move the config to lint-staged.config.js. A function receives the matched file list and returns the commands:
// lint-staged.config.js (ESM: requires "type": "module" or use .mjs)
export default {
"*.{js,mjs,cjs}": ["eslint --fix --max-warnings=0", "prettier --write"],
// Run the type checker once for the whole project, not once per file
"*.ts": () => "tsc --noEmit",
};A function that ignores its argument runs the command once without any file paths appended. That suits project-wide tools like tsc, which can't check a single file in isolation against your tsconfig.json. Remove the lint-staged key from package.json when you add this file, because lint-staged stops with an error if it finds more than one config.
Common Errors and Fixes
| Symptom | Likely cause | Fix | Column | Column |
|---|---|---|---|---|
| Hook never runs | `prepare` did not run, so `core.hooksPath` is unset | Run `npm install` or `npx husky` once | ||
| `hook was ignored because it's not set as executable` | File created on a system that dropped the execute bit | `chmod +x .husky/pre-commit` and commit the change | ||
| `lint-staged could not find any staged files` | Nothing staged, or the commit was made with `--allow-empty` | Stage files first; the message is harmless | ||
| `npm ci` fails in CI or Docker because `husky` is missing | `prepare` runs but dev dependencies are not installed | Use `"prepare": "husky \ | \ | true"`, or set `HUSKY=0` in that environment |
| Merge conflict message after fixes | A fixer changed lines that overlap an unstaged hunk | Stage the whole file or commit the unstaged hunk separately | ||
| Hook runs but `npx: command not found` in a GUI Git client | The client's shell lacks your Node `PATH` | Configure the PATH in `~/.config/husky/init.sh` |
Bypassing the hook
git commit --no-verify skips pre-commit hooks entirely. That's useful for a work-in-progress commit on a private branch. It also shows why a hook is a convenience and not a guarantee: anyone can skip it, and a contributor whose prepare never ran won't have it. The CI checks in the next chapter are what enforce the rules.
Exercise
You stage src/a.js and leave src/b.js modified but unstaged. src/a.js has one ESLint warning and no errors. With the config "*.js": ["eslint --fix", "prettier --write"], does the commit succeed, and is src/b.js touched?
Show answer
The commit succeeds, because ESLint exits with 0 when it reports only warnings. src/b.js is not touched, because lint-staged passes only staged files to the commands. Add --max-warnings=0 if warnings should block the commit.
Exercise
A teammate's config is "*.js": "npm run lint", where lint is eslint .. Commits are slow, and errors appear in files nobody changed. Why, and what is the fix?
Show answer
lint-staged appends the staged paths after eslint ., so ESLint still lints the whole project, plus the staged files. Replace the value with eslint --fix (or eslint) so that only the staged paths are linted.
Exercise
You add "*.ts": "tsc --noEmit" to the lint-staged key in package.json, and tsc ignores your tsconfig.json settings. Why does this happen, and how do you fix it?
Show answer
lint-staged appends file paths, and when tsc receives file paths it ignores tsconfig.json. Move the config to lint-staged.config.js and use a function that ignores its argument, "*.ts": () => "tsc --noEmit", so tsc runs once with no paths and reads the project config.