How to create a Typescript express server in Nodejs
First Run this command in Root directory of your project:
npm init
And then Install the necessary dependencies:
npm install express @types/express typescript ts-node nodemon --save
Create a tsconfig.json
file in the root directory of your project and add the following configurations:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"rootDir": "./",
"sourceMap": true,
"outDir": "dist",
"esModuleInterop": true,
"strict": true
}
}
Create an server.ts
file in the root directory of your project and add the following code to create an express server:
import express from "express";
const app = express();
app.get("/", (req, res) => {
res.send("Hello from Express server!");
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Express server listening on port ${port}`);
});
- In the
package.json
file, add astart
script to run the express server using nodemon:
"scripts": {
"start": "nodemon server.ts"
},
- To run the server in development mode, use the following command:
npm run start
Your express server is now created and running using typescript in nodejs.