Sub topic 2
Fixing Problems Automatically with --fix
This chapter assumes you already have ESLint installed with an eslint.config.js file. It also assumes you can run commands with npx.
Applying Autofixes
Some ESLint rules can fix their own problems. For example, eqeqeq can safely turn == into === in some cases. Run:
npx eslint . --fixESLint rewrites the files for any problem it can fix safely and then reports whatever is left. Problems such as unused variables usually stay, because fixing them would mean guessing what you meant. To preview the changes without writing anything, use --fix-dry-run.
Disabling Rules Inline, and When Not To
A directive comment turns off a rule for a single spot:
function logUser(user) {
// eslint-disable-next-line no-console
console.log(user);
}Always name the rule you are disabling. A bare // eslint-disable turns off every rule and hides real bugs. If you keep disabling the same rule, change its setting in the config.
Installing and Running Prettier
npm install --save-dev --save-exact prettier
npx prettier . --write
npx prettier . --check--write reformats the files in place. --check changes nothing. It lists the unformatted files and exits with an error code if it finds any, which makes it the right command for CI.
Configuring Prettier
Prettier has only a few options. Put them in a .prettierrc file:
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100
}Any option you leave out keeps its default value.
Ignoring Files and Code Blocks
A .prettierignore file uses .gitignore syntax, for example dist/ or coverage/. To keep one statement exactly as you wrote it, put a comment above it:
// prettier-ignore
const matrix = [
1, 0, 0,
0, 1, 0,
0, 0, 1,
];Making ESLint and Prettier Work Together
Some ESLint rules check formatting, and those can fight with Prettier's output. The eslint-config-prettier package turns off every one of those rules. Install it with npm install --save-dev eslint-config-prettier, then add it as the last entry so it overrides the configs before it:
// eslint.config.js
import js from "@eslint/js";
import eslintConfigPrettier from "eslint-config-prettier";
export default [
js.configs.recommended,
eslintConfigPrettier,
];Exercise
You run npx eslint . --fix and one no-unused-vars warning is still reported. Why, and what should you do?
Show answer
ESLint does not autofix that rule because removing the variable could change what you meant. Delete or use the variable yourself, or disable the rule with a named directive comment only if you have a real reason.
Exercise
Which Prettier command should a CI job run, and why?
Show answer
npx prettier . --check. It changes no files and exits with an error code when any file is unformatted, so the build fails.