This website collects cookies to deliver better user experience
How to Create a TypeScript Project with ExpressJS the Simplest Way!! By SilvenLEAF
How to Create a TypeScript Project with ExpressJS the Simplest Way!! By SilvenLEAF
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 typescript version of node 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
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
importexpress,{Request,Response}from'express';importpathfrom'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!`})});// --------------------ListenconstPORT= process.env.PORT||5000;app.listen(PORT,()=>{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/home and test it out yourself. Enjoy!