How to Build Express JS Server with Typescript
GihanRangana
Posted on October 23, 2023
If you're looking for a quick and easy way to get started with Express JS, then this video is for you! We'll walk you through the steps necessary to build an Express JS server with Typescript, and by the end of the video, you'll have a working server ready to go!
Setup
Initialize NPM Project
npm init -y
npm install --dev typescript ts-node @types/node
Adding tsconfig.json
npx tsc --init
tsconfig.json
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2020",
"sourceMap": true,
"outDir": "dist"
},
"include": [
"src/**/*"
]
}
Configure nodemon to restart the server automatically when adding changes to files.
npm install --dev nodemon
nodemon.json
{
"watch": [
"src/**/*"
],
"exec": "npm run start:dev",
"ext": "js,ts,json"
}
Scripts on package.json
"scripts": {
"build": "tsc",
"start:dev": "ts-node src/index.ts",
"dev": "nodemon",
"start":"npm run build && node ./dist/index.js"
}
Install and config Express Js
npm install express dotenv
type definitions for express
npm install --dev @types/express
src/index.ts
import express from 'express';
import dotenv from 'dotenv'
dotenv.config()
const app = express()
app.get('/', (req, res) => {
res.send("Welcome to TS Server Updated!!!")
})
app.listen(process.env.PORT,() => {
console.log(`TS Server listening on ${process.env.PORT}`)
})
.env
PORT=3000
Finally
npm run dev
to run dev mode
npm start
to production mode
💖 💪 🙅 🚩
GihanRangana
Posted on October 23, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.