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
#Step 1 : Initialize the project
mkdir my-project
cd my-project
npm init -y
#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
#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`
#Step 4 : Initialize typescript
tsc --init
#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"]
}
#Step 6 : Initialize eslint configuration
npx eslint --init
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)
#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,
},
],
},
},
];
#Step 8 : Setup Prettier
npm install --save-dev prettier
#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
}
#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"
}
# 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;
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';
import path from 'path';
dotenv.config(
{
path : path.join(process.cwd(), ".env")
}
);
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 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
mongoose Article's
30 articles in total
Crudify: Automate Your Mongoose CRUD Operations in NestJS
read article
6 Steps to Set Up MongoDB Atlas for Node.js Applications
read article
Mysql 101 for Mongoose developer.
read article
Tutorial de Instalação: Express com MongoDB e Mongoose
read article
Today’s new knowledge #6(Mongoose)
read article
Today’s new knowledge #10 (Building a Flexible Query Builder for MongoDB with Mongoose)
read article
mongoose connect to express
read article
I Fumbled on a Next.js MongoDB Error and Learned the Key Differences Between Mongoose and MongoClient
read article
Setup Eslint Prettier in a TypeScript project with mongoose ODM
currently reading
Bootcamping 01: An Unexpected Behavior of Mongoose
read article
Common Myths About Mongoose
read article
5 Quick And Easy MongoDB Optimizations (part 1)
read article
Mongoose Interview Questions
read article
MongoDB vs. Mongoose: Understanding Their Roles and Differences
read article
We finally have a fullstack framework for MongoDB
read article
Mongoose
read article
💬 Building a Real-time Chat Feature for Virtual Gift Store Using Socket.IO with MERN Stack 🚀
read article
The Power of exec() in Mongoose: Unlocking Better Query Execution
read article
Enhancing Mongoose Reference Handling in Node.js
read article
Mongoose Documentation
read article
How to Connect MongoDB with Node.js: A Comprehensive Guide
read article
Updating Non-Primitive Data in an Array Using Transactions and Rollbacks
read article
Method Chaining in Mongoose: A Brief Overview
read article
Understanding Transactions and Rollbacks in MongoDB
read article
Understanding Populating Referencing Fields in Mongoose
read article
How to Use Bcrypt for Password Hashing in Node.js
read article
Getting Started with Mongoose
read article
Running Unit Tests with MongoDB in a Node.js Express Application using Jest
read article
Setting up MongoDB using Mongoose in Node.js
read article
I built an open-source schema visualisation tool for mongoose
read article
Featured ones: