Sub topic 6
Fixing Problems Automatically with --fix
ESLint can repair many of the problems it reports by itself. This chapter covers how the --fix flag works, which problems it can and cannot repair, and how to preview and limit fixes before they touch your files.
This chapter assumes you have ESLint installed with a working eslint.config.js, and that you know how to turn rules on and set their severity. It also assumes you can run commands with npx and read ESLint's terminal output.
What --fix actually does
When a rule finds a problem, it can attach a fix to the report. A fix is a small text edit: replace the characters in this range with this new text. Running npx eslint . --fix tells ESLint to apply those edits and write the changed files back to disk. Anything it cannot repair is still printed as a normal problem.
Each rule's documentation marks it as fixable (shown with a wrench icon) or as offering suggestions (shown with a light bulb icon). Many rules are neither. no-unused-vars is one example: ESLint cannot know whether you meant to delete the variable or meant to use it.
| Kind of report | Applied by `--fix`? | Where you use it | Example rules |
|---|---|---|---|
| Fix | Yes | CLI, editor, Node API | `no-var`, `prefer-const`, `object-shorthand` |
| Suggestion | No | Editor quick-fix menu, Node API | `no-useless-escape` |
| Neither | No | You edit the code by hand | `no-undef`, most `eqeqeq` cases |
The difference between the first two rows is intentional. A fix is supposed to be safe, meaning it should not change what the program does. When a rule's edit could change behavior, the rule offers it as a suggestion. For example, no-useless-escape cannot tell whether "\d" should lose the backslash or gain a second one, so it offers both options and lets you choose.
A worked example
Here is a config that turns on four rules:
// eslint.config.js
export default [
{
files: ["**/*.js"],
languageOptions: { ecmaVersion: "latest", sourceType: "module" },
rules: {
"no-var": "error",
"prefer-const": "error",
"object-shorthand": "error",
eqeqeq: ["error", "always"],
},
},
];And here is a file that breaks all four:
// src/cart.js
var taxRate = 0.2;
let items = [];
export function addItem(name, price) {
var item = { name: name, price: price };
items.push(item);
return item;
}
export function total() {
let sum = 0;
for (const item of items) sum += item.price;
return sum * (1 + taxRate);
}
export function isEmpty() {
return items.length == 0;
}Run the fixer:
npx eslint src/cart.js --fixThe file now reads:
// src/cart.js
const taxRate = 0.2;
const items = [];
export function addItem(name, price) {
const item = { name, price };
items.push(item);
return item;
}
export function total() {
let sum = 0;
for (const item of items) sum += item.price;
return sum * (1 + taxRate);
}
export function isEmpty() {
return items.length == 0;
}The terminal still shows one problem:
src/cart.js
18:23 error Expected '===' and instead saw '==' eqeqeq
✖ 1 problem (1 error, 0 warnings)This output shows three things about how fixing behaves:
var taxRatebecameconst, notlet.no-varfirst rewrote it aslet. On a later pass,prefer-constsaw that the binding is never reassigned and changed it toconst. ESLint chains fixes in this way.itemsbecameconsteven though the code callsitems.push.prefer-constonly checks whether the binding is reassigned. Mutating the array does not count.sumis reassigned, so it stayslet.==was not fixed.eqeqeqonly autofixes comparisons where==and===are guaranteed to behave the same, such astypeof x == "string". Changingitems.length == 0is probably safe, but the rule cannot prove that, so it leaves the change to you.
Because an error remains, ESLint exits with code 1. A script or CI job running --fix will still fail if a problem cannot be fixed.
How fixes are applied internally
ESLint lints the file, collects every fix, and sorts the fixes by position. It applies each fix whose text range does not overlap a fix it already applied in that pass. Overlapping fixes are skipped. ESLint then lints the new text again and repeats. It stops when a pass produces no new fixes, or after 10 passes, whichever comes first.
This design has two practical effects. First, two rules that fix the same code never corrupt each other, because the second fix waits for the next pass and sees the updated text. Second, a pair of rules whose fixes undo each other will go back and forth until the 10-pass limit runs out. You will then see their errors even after running --fix. This happens most often when two configs disagree about style, which is one reason later chapters hand formatting to Prettier only.
Previewing fixes without writing
--fix-dry-run calculates fixes the same way but never writes to disk. The default output only lists the problems that would remain, so pair it with the JSON formatter. The JSON output includes an output property containing the fixed source:
npx eslint src/cart.js --fix-dry-run --format json \
| node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{for(const r of JSON.parse(s)){if(r.output)console.log(r.filePath+"\n"+r.output)}})'A file without an output property had nothing to fix. Dry runs are also how editor integrations and other tools receive fixed text without ESLint writing to disk directly.
Limiting which fixes run
By fix type
Each rule declares a meta.type: problem (likely bugs), suggestion (better ways to write code), or layout (whitespace and punctuation). The --fix-type flag applies only fixes from the categories you list. It also accepts directive, which covers removing unused eslint-disable comments.
npx eslint . --fix --fix-type layout,directiveThis lets you land low-risk changes in one commit and review riskier ones separately. Unused disable comments are reported as warnings by default in ESLint 9, and the directive type removes them.
By rule, with the Node API
The CLI cannot fix only one rule while still reporting all the others, but the Node API can. The fix option accepts a function that receives each problem and returns whether to apply its fix:
// fix-selected.mjs
import { ESLint } from "eslint";
const eslint = new ESLint({
fix: (message) => message.ruleId === "object-shorthand",
});
const results = await eslint.lintFiles(["src/**/*.js"]);
await ESLint.outputFixes(results);
const formatter = await eslint.loadFormatter("stylish");
console.log(await formatter.format(results));Run it with node fix-selected.mjs. Only the shorthand fixes are written. Every other problem is still reported. This works well for a large migration where each rule's fixes should go into a separate commit that is easy to review.
Common mistakes
- Expecting
--fixto clear every error. It only applies fixes that rules offer. Read what remains after it runs. - Treating fixes as proof of correctness. Fixes are designed to preserve behavior, but plugin rules vary in quality. Review the diff, especially after you add a new plugin.
- Fixing in CI. A CI job that runs
--fixchanges files that nobody commits, so the check passes while the repository stays broken. Run plaineslintin CI and run--fixlocally. - Rules fighting each other. If the same errors come back after every
--fix, two rules probably disagree. Turn one of them off.
Exercise
After running npx eslint . --fix, a file still contains let count = 0; and count is never reassigned, even though prefer-const is set to "error". The report shows no prefer-const error for it. What is the most likely reason?
Show answer
The prefer-const rule is not running on that file. The likely causes are that the file does not match the files pattern of the config object that enables the rule, or that a later config object or an inline directive turns the rule off. If the rule were running, it would either fix the line or report it.
Exercise
Why does eqeqeq fix typeof x == "string" but not a == b, and how can you apply only the fixes for object-shorthand across a codebase while still seeing every other error?
Show answer
typeof always returns a string, so == and === give the same result when comparing it to a string literal. That makes the fix safe. For a == b, type coercion might matter, so the rule cannot prove the change is safe. To fix only one rule, use the Node API with a fix function such as (m) => m.ruleId === "object-shorthand", then call ESLint.outputFixes(results) and format the results to print the remaining problems.