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

npm install eslint --save-dev

2. Initialize ESLint

npx eslint --init

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

npm install --save-dev 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

npm install --save-dev eslint-config-prettier eslint-plugin-prettier

Update .eslintrc.json:



 


๐Ÿงช Linting & Formatting Commands

Add the following scripts to package.json:



 

Now run:

Run linter

npm run lint

Auto-fix lint issues

npm run lint:fix

Format code

npm run format

๐Ÿ“ฆ 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:

npm install --save-dev eslint-plugin-node eslint-plugin-import

๐Ÿ” Security Linting (Highly Recommended)

Install:

npm install --save-dev eslint-plugin-security

Add to config:

"plugins": ["security"]

โšก 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

You may also like...