Create a server using NodeJS and Typescript

Create a server using NodeJS and Typescript

Step 1: Set up a new project folder Create a new folder for your project and navigate to it in your terminal.

Step 2: Initialize the project Run the following command to initialize a new Node.js project with npm:

npm init -y

Step 3: Install dependencies Install the required dependencies for the project:

npm install express typescript nodemon --save-dev

Step 4: Create a TypeScript configuration file Create a file named tsconfig.json in the root of your project and add the following configuration:

{
  "compilerOptions": {
    "target": "ES2021",
    "module": "commonjs",
    "outDir": "dist",
    "strict": true,
    "esModuleInterop": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

Step 5: Create the source files Create a folder named src in the root of your project and create a file named app.ts inside the src folder. This will be your main application file. Add the following code to it:

import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello, world!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Step 6: Add a start script Open the package.json file and add the following "start" script inside the "scripts" section:

"scripts": {
  "start": "nodemon --exec ts-node src/app.ts"
}

Step 7: Start the server To start the server, run the following command in your terminal:

npm start

Now, whenever you make changes to your TypeScript files, Nodemon will automatically restart the server for you, so you don't have to do it manually.

That's it! You now have a Node.js and TypeScript setup with Nodemon to avoid manually restarting the server every time you make changes. Feel free to customize and expand on this setup as needed for your project.