DEV Community

Cover image for How to Build Express JS Server with Typescript
GihanRangana
GihanRangana

Posted on

How to Build Express JS Server with Typescript

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
Enter fullscreen mode Exit fullscreen mode

Adding tsconfig.json

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

tsconfig.json

{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "target": "ES2020",
    "sourceMap": true,
    "outDir": "dist"
  },
  "include": [
    "src/**/*"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Configure nodemon to restart the server automatically when adding changes to files.

npm install --dev nodemon
Enter fullscreen mode Exit fullscreen mode

nodemon.json

{
    "watch": [
        "src/**/*"
    ],
    "exec": "npm run start:dev",
    "ext": "js,ts,json"
}
Enter fullscreen mode Exit fullscreen mode

Scripts on package.json

"scripts": {
    "build": "tsc",
    "start:dev": "ts-node src/index.ts",
    "dev": "nodemon",
    "start":"npm run build && node ./dist/index.js"
}
Enter fullscreen mode Exit fullscreen mode

Install and config Express Js

npm install express dotenv
Enter fullscreen mode Exit fullscreen mode

type definitions for express

npm install --dev @types/express
Enter fullscreen mode Exit fullscreen mode

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}`)
})
Enter fullscreen mode Exit fullscreen mode

.env

PORT=3000
Enter fullscreen mode Exit fullscreen mode

Finally

npm run dev to run dev mode
npm start to production mode

Top comments (1)

Collapse
 
dotenv profile image
Dotenv

💛🌴