In modern development, we use tools to automate code quality checks. The two most important tools for this are linters and formatters. They do different but complementary jobs.
What is a Linter? Meet ESLint
A linter is a tool that analyzes your code to find problems. It's like a grammar checker for your code. ESLint is the most popular linter for JavaScript.
It can catch:
- Potential Bugs: Code that is syntactically valid but likely a mistake (e.g., using a variable before it's defined, creating infinite loops).
- Best Practice Violations: Code that works but doesn't follow recommended practices (e.g., using var instead of let or const).
- Stylistic Issues: Code that doesn't conform to a specific style guide (e.g., using single quotes instead of double quotes).
You configure ESLint with a .eslintrc.json (or .js) file where you define the rules you want to enforce.
JSON
// .eslintrc.json
{
"extends": [
"eslint:recommended", // ESLint's recommended baseline rules
"plugin:react/recommended" // Recommended rules for React
],
"rules": {
"semi": ["error", "always"], // Enforce semicolons at the end of statements
"quotes": ["error", "single"], // Enforce single quotes
"no-unused-vars": "warn" // Warn about unused variables instead of causing an error
},
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"env": {
"browser": true,
"node": true
}
}
ESLint can often automatically fix the problems it finds!
What is a Formatter? Meet Prettier
A formatter is a tool that enforces a consistent code style. It doesn't care if your code is "correct" or not; it only cares about how it looks. Prettier is an "opinionated" code formatter.
It automatically reformats your code to ensure it follows a consistent style for things like:
- Tab width vs. spaces
- Maximum line length
- Quote style (single vs. double)
- Trailing commas
- Spacing around brackets and parentheses
You configure Prettier with a .prettierrc file. Its options are intentionally limited because its goal is to stop all arguments about code style.
JSON
// .prettierrc
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5"
}
ESLint vs. Prettier: The Perfect Team
- ESLint: Finds bugs and enforces best practices (Code Quality).
- Prettier: Formats your code to look consistent (Code Style).
They work best together! You format your code with Prettier first, and then ESLint checks for any logical errors. There are plugins like eslint-config-prettier that turn off any ESLint style rules that conflict with Prettier, letting each tool do what it does best.
You can set up your code editor (like VS Code) to run these tools automatically every time you save a file.