Logo

dev-resources.site

for different kinds of informations.

Setup Eslint Prettier in a TypeScript project with mongoose ODM

Published at
11/17/2024
Categories
typescript
mongoose
eslint
prettier
Author
rashedul_islam_rajj
Author
19 person written this
rashedul_islam_rajj
open
Setup Eslint Prettier in a TypeScript project with mongoose ODM

#Step 1 : Initialize the project

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

#Step 2 : Install necessary packages

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

#Step 3 : Create a folder structure

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

#Step 4 : Initialize typescript

tsc --init
Enter fullscreen mode Exit fullscreen mode

#Step 5 : Configure TypeScript

Modify tsconfig.json with this following settings

{
  "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 6 : Initialize eslint configuration

npx eslint --init
Enter fullscreen mode Exit fullscreen mode

Answer following questions like this

How would you like to use ESLint? 
--> To check syntax and find problems
What type of modules does your project use? 
-->JavaScript modules (import/export) //(you can require syntax by selecting commonjs) 
 Which framework does your project use?
--> None of these
Does your project use TypeScript? 
--> yes
Where does your code run?
--> node
Would you like to install them now?
--> yes
Which package manager do you want to use?
--> npm //(you can choose pnpm or yarn)
Enter fullscreen mode Exit fullscreen mode

#Step 7 : Configure the eslint.config.mjs file

import typescriptEslint from '@typescript-eslint/eslint-plugin';
import globals from 'globals';
import tsParser from '@typescript-eslint/parser';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import js from '@eslint/js';
import { FlatCompat } from '@eslint/eslintrc';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
  baseDirectory: __dirname,
  recommendedConfig: js.configs.recommended,
  allConfig: js.configs.all,
});

export default [
  {
    ignores: ['**/node_modules', '**/dist'],
  },
  ...compat.extends(
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier',
  ),
  {
    plugins: {
      '@typescript-eslint': typescriptEslint,
    },

    languageOptions: {
      globals: {
        ...globals.node,
        process: 'readonly',
      },

      parser: tsParser,
      ecmaVersion: 'latest',
      sourceType: 'module',
    },

    rules: {
      'no-unused-vars': 'off',
      'prefer-const': 'warn',
      'no-console': 'off',
      'no-undef': 'error',
      semi: ['warn', 'always'],
      '@typescript-eslint/no-empty-object-type': 'off',
      '@typescript-eslint/no-unused-vars': 'off',
      '@typescript-eslint/no-unused-expressions': [
        'warn',
        {
          allowShortCircuit: true,
          allowTernary: true,
          allowTaggedTemplates: true,
        },
      ],
    },
  },
];


Enter fullscreen mode Exit fullscreen mode

#Step 8 : Setup Prettier

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

#Step 9 : Create .prettierrc file for better customization (optional)

Create .prettierrc configuration file and apply following settings

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

#Step 10 : Add scripts to package.json file

"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

# Sample Files

app.ts

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

const app : Application = 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';
import path from 'path';

dotenv.config(
    {
        path : path.join(process.cwd(), ".env")
    }
);

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 11 : Run 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
mongoose Article's
30 articles in total
Favicon
Crudify: Automate Your Mongoose CRUD Operations in NestJS
Favicon
6 Steps to Set Up MongoDB Atlas for Node.js Applications
Favicon
Mysql 101 for Mongoose developer.
Favicon
Tutorial de Instalação: Express com MongoDB e Mongoose
Favicon
Today’s new knowledge #6(Mongoose)
Favicon
Today’s new knowledge #10 (Building a Flexible Query Builder for MongoDB with Mongoose)
Favicon
mongoose connect to express
Favicon
I Fumbled on a Next.js MongoDB Error and Learned the Key Differences Between Mongoose and MongoClient
Favicon
Setup Eslint Prettier in a TypeScript project with mongoose ODM
Favicon
Bootcamping 01: An Unexpected Behavior of Mongoose
Favicon
Common Myths About Mongoose
Favicon
5 Quick And Easy MongoDB Optimizations (part 1)
Favicon
Mongoose Interview Questions
Favicon
MongoDB vs. Mongoose: Understanding Their Roles and Differences
Favicon
We finally have a fullstack framework for MongoDB
Favicon
Mongoose
Favicon
💬 Building a Real-time Chat Feature for Virtual Gift Store Using Socket.IO with MERN Stack 🚀
Favicon
The Power of exec() in Mongoose: Unlocking Better Query Execution
Favicon
Enhancing Mongoose Reference Handling in Node.js
Favicon
Mongoose Documentation
Favicon
How to Connect MongoDB with Node.js: A Comprehensive Guide
Favicon
Updating Non-Primitive Data in an Array Using Transactions and Rollbacks
Favicon
Method Chaining in Mongoose: A Brief Overview
Favicon
Understanding Transactions and Rollbacks in MongoDB
Favicon
Understanding Populating Referencing Fields in Mongoose
Favicon
How to Use Bcrypt for Password Hashing in Node.js
Favicon
Getting Started with Mongoose
Favicon
Running Unit Tests with MongoDB in a Node.js Express Application using Jest
Favicon
Setting up MongoDB using Mongoose in Node.js
Favicon
I built an open-source schema visualisation tool for mongoose

Featured ones: