How to setup typescript with nodejs and expressjs?
Omkar Lanjekar·Mar 15th 25·
typescript setup nodejstypescrpt with expressjstypescript setup
In this blog we will learn how to setup typescript wth nodejs and expressjs app.
First we have to download nodejs
From this website we can download nodejs:
Now create a folder expressjswithtypescript and open command line in that folder
Now we will create package.json file using npm init --y
npm init --y
Now install this packages using command line
npm install cors express ts-node
npm install -D @types/cors @types/express @types/node ts-node-dev tsconfig-paths typescript
Now add this code to scripts object in package.json file
"dev":"ts-node-dev --respawn src/server.ts",
"build":"tsc",
"start":"node build/src/server.js"
Your final package.json will look something like this:
{
"name": "expressjswithtypescript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev":"ts-node-dev --respawn src/server.ts",
"build":"tsc",
"start":"node build/src/server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
"ts-node": "^10.9.2"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^5.0.0",
"@types/node": "^22.13.9",
"ts-node-dev": "^2.0.0",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.8.2"
}
}
Now we will we create tsconfig.json file using npx tsc --init command line
npx tsc --init
Now uncomment the below fields and replace below fields with this new value in tsconfig.json file
"outDir": "./build"
"rootDir": "./"
Now create src folder in root of the project. And inside src folder create server.ts file
// src/server.ts
import express, { Request, Response } from "express";
const app = express();
import cors from "cors";
const PORT = process.env.PORT || 8000;
app.use(cors());
app.get("/", (req: Request, res: Response) => {
res.status(200).json({
success: true,
message: "API is working fine.",
});
});
app.listen(PORT, () => {
console.log(`API is working on PORT ${PORT}`);
});
Command to run development server:
npm run dev
Command to do production build and it will create build folder:
npm run build
Command to run production build:
npm run start