If you're a beginner on typescript or some veteran who tends to forget how to setup a typescript server the you've come to the right place.
Here are the steps to create a typescript server up and running:
- Make a folder then, initialize the node project
npm init -y
- Install dependencies, in this case I'm installing expressjs as my web app framework but feel free to use others like fastify
npm i express cors dotenv
npm i -D typescript @types/node @types/express concurrently
- Initialize tsconfig
npx tsc --init
- Edit tsconfig.json
"outDir": "./dist"
- Edit package.json scripts
"scripts": {
"build": "npm install typescript && npx tsc",
"start": "node dist/index.js",
"dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/index.js\""
}
- Create a file named index.ts, this will server as the root file for your server. Paste this inside index.ts.
import express, { Express } from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import http from 'http';
dotenv.config();
const app: Express = express();
const port = process.env.PORT ?? 5905;
app.use(cors());
const server = http.createServer(app);
server.listen(port, () => {
console.log(`⚡️[server]: Server is running at http://localhost:${port}`);
});
- Run build
npm run build
- Finally run the server
npm run dev
Latest comments (0)