How To Use TypeScript with Node.js

Harness the power of TypeScript to build robust and scalable Node.js applications with this brief introduction to ts-node.

Dr. Derek Austin 🥳
Totally TypeScript
Published in
5 min readMay 11

Photo by Yoav Hornung on Unsplash

Introduction: TypeScript with Node.js === ts-node

As an advanced developer, you already know the benefits of using TypeScript in your projects. In this article, we’ll dive into integrating TypeScript with Node.js, covering the essentials of setting up a TypeScript project, integrating it with popular Node.js frameworks, and debugging TypeScript code in a Node.js environment.

Setting Up a TypeScript Project

To kick things off, let’s create a new TypeScript project:

Step 1. Install TypeScript globally:

npm install -g typescript

Step 2. Initialize a new TypeScript project:

tsc --init

I recommend running this command from your project’s folder. In my case, I made a new ts-test folder in my regular dev folder.

Step 3. Configure tsconfig.json to target Node.js:

{
"compilerOptions": {
"module": "commonjs",
"target": "ES2020",
"moduleResolution": "node",
"esModuleInterop": true,
"outDir": "dist",
"sourceMap": true
}
}

The esModuleInterop flag here is important because it will prevent compiler errors, but the rest of the flags are more self-explanatory.

Step 4. Install Node.js type definitions:

npm install --save-dev @types/node

Using TypeScript with Node.js Framework Express

Let’s explore integrating TypeScript with Express, a popular Node.js framework used for middleware. First, install the required packages:

npm install express
npm install --save-dev @types/express

Now, create an app.ts file and import the required modules:

import express from 'express';
import { Request, Response } from 'express';

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

app.get('/', (req: Request, res: Response) => {
res.send('Hello TypeScript and Node.js!');
});

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

Compile and run the project:

tsc && node dist/app.js

Understanding ts-node

ts-node is a TypeScript execution engine and REPL for Node.js. It enables you to execute TypeScript files directly, without having to compile them to JavaScript first. By using ts-node, you can speed up your development process and easily test your code without the extra compilation step.
To use ts-node, first install it as a development dependency:

npm install --save-dev ts-node

Now, you can execute TypeScript files directly using ts-node:

npx ts-node app.ts

Previously, we installed TypeScript globally, which is why we could run tsc without the prefix npx. In this case, we only installed ts-node as a local package dependency, so we execute it using npx ts-node.

Introducing ts-node-dev

ts-node-dev is a development tool built on top of ts-node. It provides features like hot-reloading and faster TypeScript compilation, making your development process even smoother. It restarts the target node process when any TypeScript file is changed, while preserving the state of your application between restarts.

To use ts-node-dev, first install it as a development dependency:

npm install --save-dev ts-node-dev

Now, you can use ts-node-dev to run your TypeScript project:

npx ts-node-dev src/app.ts

Your server will automatically restart whenever you make changes to your TypeScript files.

Debugging TypeScript Code in a Node Environment

To debug your TypeScript code in Node.js, use the inspect flag along with the sourceMap option:

  1. We already installed ts-node and ts-node-dev in the last section:
npm install --save-dev ts-node ts-node-dev

2 — Modify your package.json to include this scripts section:

{
"scripts": {
"debug": "ts-node-dev --respawn --transpile-only --inspect=9230 app.ts",
"start": "node --inspect-brk -r ts-node/register app.ts"
}
}

3 — Start the server in debug mode:

npm run debug

Attaching a Debugger

To attach a debugger to your running Node.js process, you can use either Chrome DevTools or Visual Studio Code. Make sure your debug server is running with the command from the last section.

Chrome DevTools

Step 1. Open Chrome and navigate to chrome://inspect.

Step 2. Click on “Open dedicated DevTools for Node.”

Step 3. In the newly opened DevTools window, click on the “Connections” tab and then the blue “Add connection” button.

Step 4. Enter localhost:9230 (the port you specified in your package.json debug script) and click “Add.”

Step 5. Your TypeScript application should now appear under the “Sources” tab, which will automatically be opened to the “Node” tab. You’ll be able to see the app.ts file right there along with the Console for debugging.

Visual Studio Code

Step 1. Open your TypeScript project’s folder in Visual Studio Code.

Step 2. Click on the “Run” tab on the left-hand side or press Ctrl+Shift+D. (Cmd+Shift+D on Mac).

Step 3. Click the “create a launch.json file” link and select “Node.js” as the environment.

Step 4. Modify the generated launch.json configuration:

{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Attach to TS Node",
"address": "localhost",
"port": 9230,
"localRoot": "${workspaceFolder}",
"remoteRoot": "${workspaceFolder}",
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/dist/**/*.js"]
}
]
}

Step 5. Save the launch.json file.

Step 6. With your application running in debug mode, click on the green “Run” button (a green arrow), next to “Attach to TS Node” in the top left corner. VS Code will now attach its debugger to your running process.

Configuring TypeScript To Work Better With Node

In more complex projects, you might want to fine-tune your TypeScript configuration to suit your needs. Here are a few settings you can add to your tsconfig.json file:

  • "strict": true – Enforces strict type checking, helping you catch more errors during the development process.
  • "baseUrl": "./src" – Specifies the base URL for module resolution, allowing for cleaner imports in your project.
  • "esModuleInterop": true – Allows default imports to work correctly with CommonJS modules.
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2020",
"moduleResolution": "node",
"outDir": "dist",
"sourceMap": true,
"strict": true,
"baseUrl": "./src",
"esModuleInterop": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}

Conclusion: TypeScript with Node.js === ts-node

By utilizing TypeScript with Node.js, you can harness the full potential of both technologies to build powerful, maintainable, and scalable applications. With the help of ts-node, you can seamlessly integrate TypeScript into your Node.js workflow and unlock features like type safety, improved IDE support, and robust debugging capabilities.

As a developer, embracing TypeScript and Node.js together, along with tools like ts-node-dev, allows you to keep your code clean, maintainable, and less error-prone. Take advantage of this powerful combination to elevate your development experience and create high-quality projects.

Happy coding! 🥳

Dr. Derek Austin 🥳
Totally TypeScript

I love working with Next.js + Tailwind CSS ♦ Lead Frontend Developer ♦ React Software Engineer ♦ SEO & Web Performance Expert ♦ I love accessible websites