Step-by-Step Guide to Setting Up Nodejs with Expressjs

If you are new to Nodejs and Expressjs, this guide will help you set up your project step by step. Let’s begin by installing the necessary packages and libraries.

Step 1: Install Required Packages

First, open your terminal and run the following command:

sh
npm install typescript @types/node @types/express express mongoose @types/mongoose nodemon@types/nodemon ts-node @types/ts-node

What Do These Packages Do?

  • TypeScript – Since we are using TypeScript, we need this package.
  • Express – A fast and flexible web framework for Node.js.
  • Mongoose – A library to interact with MongoDB.
  • Nodemon – A tool that automatically restarts your server when you make changes.
  • ts-node – Allows running TypeScript directly without manually compiling it into JavaScript.

Why Do We Need Nodemon?

Imagine you are writing code for a server. Normally, every time you make a small change, you need to manually restart the server to see the updates. This is time-consuming and slows down development.

The solution? Nodemon! 🚀

Nodemon automatically detects changes and restarts the server for you, making development faster and smoother.

Why Do We Need ts-node?

By default, Node.js cannot run TypeScript directly. You must first compile TypeScript to JavaScript before running the code. Doing this manually every time is frustrating.

The solution? ts-node!

With ts-node, you can run TypeScript files directly, without converting them to JavaScript first. This makes development much easier.


Step 2: Create an Entry File

Now, we need to create the main file for our Node.js and Express application. This is where the code execution will start.

📌 Example: Create a file named index.ts

Inside index.ts, you will write the logic for your Node.js app.

Step 3: Running the File

Now, how do we run this file? Here’s how:

1️⃣ Using Node.js (Without TypeScript)

sh
node index.js

2️⃣ Using ts-node (For TypeScript Projects)

sh
ts-node index.js

3️⃣ Using Nodemon (To Auto-Reload on Changes)

sh
nodemon –exec ts-node index.js

This command will:
✔ Start your Node.js server
✔ Watch for file changes
✔ Restart the server automatically when changes are detected


Conclusion

You have now successfully set up a Nodejs & Expressjs app with TypeScript. By using Nodemon and ts-node, you can develop faster without manually restarting the server or compiling TypeScript files.

✅ Next Step: Start writing your Express API routes and connect to MongoDB! 🚀

Let me know if you need help with the next steps. Happy coding! 🎯

Facebook
WhatsApp
Twitter
LinkedIn

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top