An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
How to Create a TypeScript Project with ExpressJS the Simplest Way!!
If you are wondering how to create a TypeScript BackEND project, fear not my brave knight. It's way easier than you can ever imagine!! Let go!
Step 1
First init our project by running npm init -y on our terminal, it'll create a package.json file. Then let's install these packages by running the following command on our terminal
npm i typescript ts-node express @types/node @types/express
typescript is the core package for typescript, ts-node is the node version for runnig .ts files just as we do with node app.js, in this case we do, ts-node app.ts. @types/node and @types/express has all the types for node and express respectively. You say why? Well typescript is all about type na :)
Bonus Step
Now let's install some helping dev stuff
npm i --D nodemon ts-node-dev
ts-node-dev package binds nodemon with typescript. The typescript version for nodemon app.js is ts-node-dev app.ts
Now let's update our package.json file
....keep others unchanged "main": "app.ts", "scripts": { "start": "ts-node app.ts", "dev": "ts-node-dev app.ts" }, ...keep others unchanged
Step 2
Run the following command, it'll will create a tsconfig.json file.
tsc --init
Step 3
Let's create an express App
Write these on the app.ts file that we created
import express, { Request, Response } from 'express';import path from 'path';// -------------------firing express appconst app = express();app.use(express.json());app.use(express.urlencoded({extended:false}));app.use(express.static(path.join(__dirname, 'client/build')));// -------------------routesapp.get('/home', (request: Request, response: Response)=>{ console.log(request.url) response.json({ message: `Welcome to the home page!` })});// --------------------Listenconst PORT = process.env.PORT || 5000;app.listen(5000, ()=>{ console.log(`Server running on PORT ${ PORT }`);})
Yippie, our very first typescript express app is ready. Let's run and test it
Type either npm start or npm run dev and then go to the localhost:5000 and test it out yourself. Enjoy!
Original Link: https://dev.to/silvenleaf/how-to-create-a-typescript-project-with-expressjs-the-simplest-way-578a
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To