Step 1:
Initialize Node.js using the command npm init -y and then npm install.
Step 2:
Install typescript globally using the command npm install -g typescript
This provides the typescript compiler which makes it possible to compile Typescript code into JavaScript
Step 3:
Install the following dependencies. As you are using typescript, install all the modules using @types/ at the front in order to use import in the .ts files.
- ts-node
- express
- @types/express
- nodemon
Step 4:
Update tsconfig.json with the following settings
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"outDir": "./dist",
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
Step 5:
Update package.json file to specify the startup.
"main": "index.js",
"scripts": {
"build": "npx tsc",
"start": "node dist/index.js",
"dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/index.js\""
}
use npm run dev command to start the server after creating the index.ts file.
Step 6:
Create index.ts file with the basic code.
import express, { Express, Request, Response } from 'express';
import dotenv from 'dotenv';
dotenv.config();
const app: Express = express();
const port = process.env.PORT || 8081;
app.get('/', async (req: Request, res: Response) => {
res.send('Express + TypeScript Server');
});
app.listen(port, () => {
console.log(`⚡️[server]: Server is running at http://localhost:${port}`);
});
Step 7:
Execute the project using the command.
npm run dev
Step 8:
Output:
No comments:
Post a Comment