ESLint and Prettier are essential tools for keeping your Node.js code consistent, readable, and error-free. Letβs go step by step.
π¦ 1. Install ESLint & Prettier
npm install --save-dev eslint prettier eslint-config-prettier eslint-plugin-prettier
-
eslint
β detects errors & enforces coding standards. -
prettier
β automatically formats code. -
eslint-plugin-prettier
β integrates Prettier rules into ESLint. -
eslint-config-prettier
β disables ESLint rules that conflict with Prettier.
βοΈ 2. Initialize ESLint
npx eslint --init
Follow the prompts:
-
How would you like to use ESLint? β To check syntax, find problems, and enforce code style
-
What type of modules? β CommonJS (Node) or ES Modules
-
Framework? β None (for pure Node.js)
-
Where will your code run? β Node
-
Preferred style guide? β Standard / Airbnb / Custom
-
Format of config file β
.eslintrc.js
This creates an .eslintrc.js
config file.
π 3. Configure ESLint + Prettier
.eslintrc.js
example:
module.exports = {
env: {
node: true,
es2021: true,
},
extends: [
"eslint:recommended",
"plugin:prettier/recommended"
],
parserOptions: {
ecmaVersion: 12,
sourceType: "module",
},
rules: {
"no-unused-vars": "warn",
"no-console": "off",
},
};
"plugin:prettier/recommended"
β ensures ESLint runs Prettier rules automatically.
β‘ 4. Create Prettier Config
Optional, but useful for consistent formatting.
.prettierrc
example:
{
"semi": true,
"singleQuote": true,
"printWidth": 80,
"trailingComma": "all"
}
-
semi
β add semicolons -
singleQuote
β use single quotes -
printWidth
β line length -
trailingComma
β add commas to multi-line objects/arrays
π οΈ 5. Add Scripts in package.json
"scripts": {
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write ."
}
-
npm run lint
β check code for errors -
npm run lint:fix
β auto-fix lint issues -
npm run format
β auto-format code with Prettier
β 6. Benefits
-
Consistency: All developers follow the same style.
-
Error prevention: ESLint catches common mistakes (undefined vars, typos).
-
Automatic formatting: Prettier makes code readable without manual effort.
-
Integration: Works with most IDEs (VSCode, WebStorm) for real-time feedback.