Node.js Linting & Formatting
๐ Node.js Linting & Formatting
Linting and formatting are essential practices for writing clean, consistent, and error-free Node.js code. They help teams maintain code quality, reduce bugs, and improve readability.
This guide explains the tools, setup, and best practices used in modern Node.js projects.
โ What Is Linting?
Linting is the process of analyzing your code to detect:
-
Syntax errors
-
Bad coding patterns
-
Potential bugs
-
Style inconsistencies
Popular Linter for Node.js:
๐ ESLint
๐จ What Is Formatting?
Formatting automatically adjusts your code to follow consistent style rules like:
-
Indentation
-
Quotes (
'vs") -
Semicolons
-
Spacing
Popular Code Formatter:
๐ Prettier
๐ ๏ธ ESLint Setup (Step-by-Step)
1. Install ESLint
2. Initialize ESLint
You will be asked:
-
Type of project (CommonJS/ES Modules)
-
Framework (None/React/Vue/etc.)
-
Environment (Browser/Node)
-
Style guide (Airbnb, Standard, etc.)
-
Use TypeScript? (Yes/No)
This generates an .eslintrc.json file.
๐งน Prettier Setup
1. Install Prettier
2. Create Prettier Config
Create prettier.config.cjs or .prettierrc:
๐ค Using ESLint + Prettier Together
ESLint handles code quality,
Prettier handles code formatting.
Install integration packages
Update .eslintrc.json:
๐งช Linting & Formatting Commands
Add the following scripts to package.json:
Now run:
Run linter
Auto-fix lint issues
Format code
๐ฆ Recommended ESLint Plugins for Node.js
| Plugin | Purpose |
|---|---|
| eslint-plugin-node | Node.js best practices |
| eslint-plugin-import | Manage imports correctly |
| eslint-plugin-security | Detect security issues |
| eslint-plugin-promise | Promise best practices |
| @typescript-eslint/* | TypeScript linting |
Install example:
๐ Security Linting (Highly Recommended)
Install:
Add to config:
โก VS Code Auto-Formatting Setup
To enable auto formatting on save:
Settings โ Search “Format On Save” โ Enable
Then install these extensions:
-
ESLint
-
Prettier
VS Code will automatically format/fix your code on save.
๐ Best Practices
โ Use ESLint + Prettier together
โ Always run lint & format before committing
โ Use Husky + lint-staged for pre-commit hooks
โ Use Airbnb or Standard style guides for consistency
โ Enable formatting on save in your editor
