This article is a step by step tutorial to create a express server using typescript.
Note: Typescript cannot be run directly into node runtime environment, although runtime like Deno, Bun supports typescript.
Create a folder, initialize npm
package using:
npm init --y
Let's install dependencies required to create express server.
express
, @types/express
to use type definitions, intellisense in code editor. Also few developer dependencies like typescript
to convert typescript file into javascript file, nodemon
to ease our development (it automatically watch for changes, and reload your code in runtime), concurrently
to run both the above developer dependencies simultaneously.
npm i express @types/express && npm i -d nodemon concurrently
Let's initialize typescript in the project. using the following command
npx tsc --init
A tsconfig.json
file will be created in the project. In the tsconfig.json
file uncomment outDir
line and enter a outDir (dist
here):
"outDir": "./dist"
Let's create a NPM script for this typescript express configuration.
In pacakage.json
file add following code,
"dev" : "concurrently \" tsc --watch\" \"nodemon dist/index.js\""
also remove a line
"main" : "index.js"
now the final part, create index.ts
file.
import express from "express";
const PORT = 3000;
const app = express();
app.get("/",(req,res)=>{
res.send("Hello");
}
app.listen(PORT);
Run the dev
script you just created in command line using:
npm run dev
That's it you're good to go, your express typescript server is ready at localhost, port 3000 Link
Let's Connect -
Tweet Thanks
LinkTree
Top comments (0)