DEV Community

Cover image for How to Set Up ESLint and Prettier in a TypeScript Project
FORHAD
FORHAD

Posted on • Edited on

17

How to Set Up ESLint and Prettier in a TypeScript Project

Setting up ESLint and Prettier in a TypeScript project can greatly enhance your development experience by automatically detecting and fixing various types of errors, ensuring a consistent code style, and reducing the likelihood of bugs. Here's a step-by-step guide to help you get started.

Step 1: Initialize Your Project

First, create a new project directory and initialize it with npm:

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

Step 2: Install Necessary Packages

Install the required dependencies. Some of these will be development dependencies (i.e., they are only needed during development):

npm install express mongoose cors dotenv --save
npm install typescript @types/node @types/express --save-dev
npm install -D nodemon ts-node-dev eslint @eslint/js @typescript-eslint/parser @typescript-eslint/eslint-plugin prettier
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Up Your Project Structure

Create the following folder structure:

my-project
│   .env
│   .gitignore
│   eslint.config.mjs
│   tsconfig.json
├───dist
├───src
│   │   app.ts
│   │   server.ts
│   └───config
│           index.ts
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure TypeScript

Generate a TypeScript configuration file and modify it:

tsc --init
Enter fullscreen mode Exit fullscreen mode

Update the tsconfig.json file with the following content:

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "rootDir": "./src",
    "outDir": "./dist",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Configure ESLint

Create an ESLint configuration file eslint.config.mjs and add the following content:

import eslint from "@eslint/js";
import tseslint from "@typescript-eslint/eslint-plugin";

export default {
  root: true,
  parser: "@typescript-eslint/parser",
  plugins: ["@typescript-eslint"],
  extends: [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  rules: {
    "no-unused-vars": "error",
    "no-undef": "error",
    "prefer-const": "error",
    "no-console": "warn"
  },
  ignorePatterns: ["dist", "node_modules"]
};
Enter fullscreen mode Exit fullscreen mode

Step 6: Set Up Prettier

Install Prettier:

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

Create a Prettier configuration file .prettierrc (optional, but recommended for customization):

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

Step 7: Update package.json Scripts

Add scripts to your package.json to automate tasks:

"main": "./dist/server.js",
"scripts": {
  "build": "tsc",
  "start:prod": "node ./dist/server.js",
  "start:dev": "ts-node-dev --respawn --transpile-only ./src/server.ts",
  "lint": "eslint .",
  "lint:fix": "eslint . --fix",
  "prettier": "prettier --ignore-path .gitignore --write \"./src/**/*.+(js|ts|json)\"",
  "prettier:fix": "prettier --write src"
}
Enter fullscreen mode Exit fullscreen mode

Step 8: Sample Files

app.ts

import express, { Request, Response } from 'express';

const app = express();

app.use(express.json());

app.get('/', (req: Request, res: Response) => {
  res.send('Hello from setup file');
});

export default app;
Enter fullscreen mode Exit fullscreen mode

server.ts

import mongoose from 'mongoose';
import app from './app';
import config from './config';

async function main() {
  try {
    await mongoose.connect(config.db_url as string);
    app.listen(config.port, () => {
      console.log(`Example app listening on port ${config.port}`);
    });
  } catch (err) {
    console.log(err);
  }
}

main();
Enter fullscreen mode Exit fullscreen mode

index.ts

import dotenv from 'dotenv';
dotenv.config();

export default {
  port: process.env.PORT,
  db_url: process.env.DB_URL,
};
Enter fullscreen mode Exit fullscreen mode

.env

PORT=5000
DB_URL=your_mongodb_connection_string
Enter fullscreen mode Exit fullscreen mode

.gitignore

node_modules
.env
dist
Enter fullscreen mode Exit fullscreen mode

Step 9: Running Your Scripts

Use the following commands to run your scripts:

npm run build           # Build the project before deployment
npm run start:prod      # Start the server for production
npm run start:dev       # Start the server for development
npm run lint            # Find ESLint errors
npm run lint:fix        # Fix ESLint errors
npm run prettier        # Find Prettier format errors
npm run prettier:fix    # Fix Prettier format errors
Enter fullscreen mode Exit fullscreen mode

By following these steps, you will have a fully set up TypeScript project with ESLint and Prettier, ensuring a smooth development experience with consistent code quality and style.

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video