Set up a modern, scalable backend using Node.js, Express, and TypeScript with hot-reloading and linting.
Create an initial folder and package. json
mkdir node-express-typescript
cd node-express-typescript
npm init --yes
Installing TypeScript & other dependencies
npm install express mongoose cors mongodb dotenv
npm install -D typescript ts-node-dev @types/express @types/cors
Generate tsconfig.json
npx tsc --init
Set the rootDir and outDir as src and dist folder
{
"compilerOptions": {
"outDir": "./dist"
// other options remain same
}
}
Create an Express server with a .ts extension
Create a file name index.ts open it
import express, { Express, Request, Response , Application } from 'express';
import dotenv from 'dotenv';
//For env File
dotenv.config();
const app: Application = express();
const port = process.env.PORT || 8000;
app.get('/', (req: Request, res: Response) => {
res.send('Welcome to Express & TypeScript Server');
});
app.listen(port, () => {
console.log(`Server is Fire at http://localhost:${port}`);
});
Watching file changes and build directory
npm install nodemon
After installing these dev dependencies, update the scripts in the package.json file:
{
"scripts": {
"build": "npx tsc",
"start": "node dist/index.js",
"dev": "nodemon index.ts"
}
}
To Run The Code
npm run dev
if everything if perfect you will see the message in console of
Server is Fire at http://localhost:8000
linting setup
npm install --save-dev eslint
npm init @eslint/config@latest
npx eslint . --ext .ts