DEV Community

Tuan Phan
Tuan Phan

Posted on

Setting Up ESLint and Prettier for a Clean Node.js Project

Introduction
Maintaining a consistent and clean codebase is crucial for the success of any software project. In the Node.js ecosystem, tools like ESLint and Prettier come to the rescue by helping developers catch errors, enforce coding standards, and format code consistently. In this guide, we'll walk through the steps to set up ESLint and Prettier for a Node.js project.

Prerequisites
Before we begin, ensure that you have Node.js and npm installed on your machine. If not, you can download them from nodejs.org.

Step 1: Initialize Your Node.js Project
Start by creating a new Node.js project or navigating to an existing one using the terminal:

mkdir your-project
cd your-project
npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 2: Install ESLint and Prettier
Install ESLint and Prettier as development dependencies:

npm install --save-dev eslint prettier
Enter fullscreen mode Exit fullscreen mode

Step 3: Create ESLint Configuration
Run the ESLint configuration wizard to create a .eslintrc.js file:

npx eslint --init
Enter fullscreen mode Exit fullscreen mode

Follow the prompts to configure ESLint according to your preferences.

Step 4: Install ESLint and Prettier Plugins
Install plugins that allow ESLint to work seamlessly with Prettier:

npm install --save-dev eslint-plugin-prettier eslint-config-prettier
Enter fullscreen mode Exit fullscreen mode

Step 5: Configure Prettier
Create a .prettierrc or .prettierrc.js file in your project root and configure Prettier options:

{
  "semi": false,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "all",
  "printWidth": 80
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Update ESLint Configuration
Edit your .eslintrc.js file to extend the Prettier configuration:


module.exports = {
  // ... other configurations
  plugins: ['prettier'],
  extends: ['eslint:recommended', 'plugin:prettier/recommended'],
};
Enter fullscreen mode Exit fullscreen mode

Step 7: Add npm Scripts for Linting
Update your package.json file to include npm scripts for running ESLint:


"scripts": {
  "lint": "eslint .",
  "lint:fix": "eslint --fix ."
}
Enter fullscreen mode Exit fullscreen mode

Step 8: Integrate with Your Code Editor
Install the ESLint and Prettier extensions for your code editor to receive real-time feedback.

Top comments (0)