How to Set Up ESLint and Prettier in a TypeScript Project

How to Set Up ESLint and Prettier in a TypeScript Project

Enhance Your Development Workflow with ESLint and Prettier in TypeScript

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

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

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

Step 4: Configure TypeScript

Generate a TypeScript configuration file and modify it:

tsc --init

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"]
}

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"]
};

Step 6: Set Up Prettier

Install Prettier:

npm install --save-dev prettier

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

{
  "singleQuote": true,
  "trailingComma": "all",
  "tabWidth": 2,
  "semi": true
}

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"
}

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;

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();

index.ts

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

export default {
  port: process.env.PORT,
  db_url: process.env.DB_URL,
};

.env

PORT=5000
DB_URL=your_mongodb_connection_string

.gitignore

node_modules
.env
dist

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

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.