Sub topic 1
Linters and Formatters Solve Different Problems
Prerequisites
This chapter assumes you can write modern JavaScript, including ES modules and arrow functions. You should also be comfortable running Node.js and npm from the command line, editing package.json, and using basic Git.
Two Tools, Two Jobs
A linter analyzes code for likely bugs and risky patterns, such as unused variables or loose equality (==). A formatter rewrites code layout, such as indentation, quotes, and line length, without changing what the code does. ESLint is the linter here, and Prettier is the formatter.
| Concern | Linter (ESLint) | Formatter (Prettier) |
|---|---|---|
| Finds bugs | Yes | No |
| Changes whitespace and quotes | Can, but shouldn't | Yes |
| Configurable rules | Many | Few options |
Installing and Running ESLint
Install ESLint and its supporting packages as dev dependencies, then run it on the whole project:
npm install --save-dev eslint @eslint/js globals
npx eslint .Understanding eslint.config.js
ESLint reads a flat config file, which exports an array of config objects. ESLint merges the objects in order, so later entries override earlier ones.
// eslint.config.js (requires "type": "module" in package.json, or name it eslint.config.mjs)
import js from "@eslint/js";
import globals from "globals";
export default [
js.configs.recommended,
{
files: ["**/*.js"],
languageOptions: {
ecmaVersion: "latest",
sourceType: "module",
globals: { ...globals.node },
},
rules: {
"no-unused-vars": "warn",
eqeqeq: ["error", "always"],
},
},
];The files key limits an object to matching paths. languageOptions tells ESLint which syntax and global variables to expect. Without globals.node, ESLint flags process as undefined.
Choosing Rules and Severity Levels
Each rule takes one of three severities: "off" (0), "warn" (1), or "error" (2). A warning is reported but leaves the exit code at 0. An error makes ESLint exit with code 1, which fails scripts and CI jobs. To pass options, use an array: the severity first, then the rule's options, as in ["error", "always"].
Building on Shared Configs and Plugins
A shared config is a published set of rules you spread into your array. js.configs.recommended is one example. A plugin adds new rules, such as framework-specific checks. You register a plugin under the plugins key and refer to its rules as prefix/rule-name. Put shared configs first and your own overrides after them.
Exercise
Your config sets "no-unused-vars": "warn" and ESLint reports three unused variables but nothing else. Will a CI step running npx eslint . fail? What change would make it fail?
Show answer
No. Warnings leave the exit code at 0. Changing the severity to "error" makes ESLint exit with code 1, which fails the step.