DEV Community

Cover image for A Simple Guide to Setting Up TypeScript with Node.js and Express (2024)
Ibrahim Ayuba
Ibrahim Ayuba

Posted on

A Simple Guide to Setting Up TypeScript with Node.js and Express (2024)

Typescript is the current industry standard for creating JavaScript applications. It enhances our JavaScript code by adding types, enabling us to build large-scale products that are more maintainable and less error-prone.

In this article, we will discuss how to set up a TypeScript project for an Express app in a few simple steps.

Prerequisites

  • You should have Node.js installed on your machine.
  • You should also have a basic knowledge of Node.js and Express.

Create a new folder for your project and initialize a package.json file

mkdir typescript-express-server
cd typescript-express-server
npm init -y
Enter fullscreen mode Exit fullscreen mode

The npm init -y prompt creates a new package.json file with the following content:

{
  "name": "article",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode

Install TypeScript

There are two ways to do this:

Globally

If you install TypeScript globally, you don't have to reinstall it for every project. To install TypeScript globally, run the following command:

npm i -g typescript
Enter fullscreen mode Exit fullscreen mode

Locally

You can also install TypeScript locally for only the current project using the following command:

npm i -D typescript
Enter fullscreen mode Exit fullscreen mode

Install other dependencies

npm i express; npm i -D ts-node @types/express
Enter fullscreen mode Exit fullscreen mode

The -D flag indicates that we're going to need ts-node and @types/express only in development mode. We'll use ts-node to compile and run our TypeScript code.

Generate the ts.config file

If you installed TypeScript globally, generate the tsconfig.json file with the following command:

tsc --init
Enter fullscreen mode Exit fullscreen mode

If you installed it locally, use the following command instead:

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

The ts.config serves as the configuration file for the TypeScript compiler. You can modify this file to customize the compiler settings for your project. It comes with a lot of commented-out options. Comment out and edit the following options:

{
  "compilerOptions": {
    ....

    "module": "NodeNext", 
    "rootDir": "./src",
    "moduleResolution": "NodeNext",
    "outDir": "./dist",
    ....
  }
}
Enter fullscreen mode Exit fullscreen mode

In the tsconfig.json file above, the settings:

  • "rootDir": "./src" specifies that the TypeScript compiler will look for source files in the ./src directory.
  • "outDir": "./dist" specifies that the compiled JavaScript files will be output in the ./dist directory. Later, we'll set up an npm run build command in our package.json that will trigger the compilation process, using these settings to transform our TypeScript code into JavaScript files in the ./dist directory.

File structure

Currently, here's a recommended file structure for your project, omitting the node_modules directory:

├── .env
├── .gitignore
├── package-lock.json
├── package.json
├── src
│  └── index.ts
└── tsconfig.json
Enter fullscreen mode Exit fullscreen mode

Update package.json file

{
  "name": "article",
  "version": "1.0.0",
  "main": "dist/index.js",
  "type": "module",
  "scripts": {
    "dev": "node --loader=ts-node/esm --env-file=.env --watch src/index.ts",
    "build": "tsc",
    "start": "node dist/index.js"
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode

Here's a summary of the changes made in the package.json file:

  1. Main Entry Point: Updated "main": "dist/index.js" to point to the compiled JavaScript file.
  2. Module Type: Changed "type": "module" to enable ES6 imports and exports.
  3. Scripts:
    • “dev”: Runs the development server with node and:
      • —-loader=ts-node/esm for compiling and running TypeScript code.
      • --env-file=.env to load environment variables from the .env file.
      • --watch to reload code after every change.
      • src/index.ts as the entry point.
    • “build”: Compiles TypeScript code to JavaScript and outputs it to the ./dist folder using tsc (change to npx tsc if you installed TypeScript locally on the current project).
    • “start”: Starts the server in production mode.

Create a basic server

In your src/index.ts file, write the following lines of code:

import express, { urlencoded, json } from "express";

const port = process.env.PORT || 8000;
const app = express();

app.use(urlencoded({ extended: true }));
app.use(json());

app.get("/", (req, res) => {
  res.status(200).json({ msg: "Server is up and running" });
});

app.listen(port, () => {
  console.log(`Server is listening at port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

In your .env file, write the following line:

PORT=3000
Enter fullscreen mode Exit fullscreen mode

Running the program

npm run dev
Enter fullscreen mode Exit fullscreen mode

If everything is working fine you should see Server is listening at port 3000 on your terminal.

Verify your app

Now that your application is running, you can verify that it's working by accessing the URL: http://localhost:3000/.
You can use:

  • Your web browser to open the URL and see the app in action
  • Extensions like Thunder Client or Postman to test the API endpoints

Conclusion

This article has guided you through setting up a TypeScript project with Node.js and Express.js, minimizing unnecessary package installations. You've learned to create a efficient development workflow, leveraging TypeScript's benefits while keeping your project lightweight.
I hope you found this tutorial helpful in getting started with TypeScript and Express.js. Happy coding!

Top comments (0)