Logo

dev-resources.site

for different kinds of informations.

How to Set Up ESLint and Prettier in a TypeScript Project

Published at
6/28/2024
Categories
webdev
typescript
eslint
prettier
Author
forhad96
Categories
4 categories in total
webdev
open
typescript
open
eslint
open
prettier
open
Author
8 person written this
forhad96
open
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.

eslint Article's
30 articles in total
Favicon
Just use this Next.js Eslint Configuration
Favicon
3. How to setup Jest in a Next 15 project (+ eslint for testing)
Favicon
Do me lint! 🙋‍♂️ An easy way to setup ESLint in any project.
Favicon
Restricting some syntax with ESLint
Favicon
Beyond Spellcheck: How Static Analysis Tools Enhance Collaboration in Coding
Favicon
ESlint 9
Favicon
How to Fix Common ESLint Errors: Troubleshooting Unknown or Strange Issues
Favicon
Incrementally fixing lots of ESlint errors in a clean way with ESlint Nibble
Favicon
Setup Eslint Prettier in a TypeScript project with mongoose ODM
Favicon
Vue3 + ESLint 9.13.0 + Prettier +TypeScript and VSCode Autoformat on Save
Favicon
Configurando un proyecto de React para producciĂłn
Favicon
Configurando Prettier, ESLint y Husky en Angular
Favicon
Eslint Code Insights from Bitbucket pipelines
Favicon
How to get ESLint 9.11.1 to run in Vue 3
Favicon
CĂłmo hacer que ESLint 9.11.1 funcione en Vue 3
Favicon
Performing Maintenance Task For A Large Codebase
Favicon
Setup Prettier Pada Nextjs Tailwind Project
Favicon
“Eslint-Summary” — Hack your Eslint Config
Favicon
Regras customizáveis para Prettier + Eslint em React
Favicon
Useful VS Code Extensions for JS
Favicon
ESLint 9 Flat config tutorial
Favicon
ESLint x Prettier: The Right Way To Start A JavaScript Project
Favicon
How to Set Up ESLint and Prettier in a TypeScript Project
Favicon
Customizable rules for Prettier + Eslint in React
Favicon
How to set up Eslint and prettier
Favicon
Configure Eslint, Prettier and show eslint warning into running console vite react typescript project
Favicon
Building Vue3 Component Library from Scratch #11 ESlint + Prettier + Stylelint
Favicon
Setup Eslint + Prettier for code standardization in React
Favicon
Setup Eslint + Prettier para padronização de código em React
Favicon
ESLint Plugin. What was missed in the doc?

Featured ones: