TypeScript in a Node.js Project - Robin Wieruch

TypeScript in a Node.js Project - Robin Wieruch

Setting up a TypeScript project with Node.js may seem like a hassle at first, but with the right steps, you’ll have everything running smoothly in no time. Whether you’re building a small script or a full-fledged application, this guide will walk you through the entire process.

We’ll start from scratch, configure TypeScript, and set up a simple development environment with best practices. Let’s dive in!

First, you need a dedicated folder for your project. Open your terminal and run the following commands:

Let’s break down what each command does:

This package.json file is essential for a Node.js project as it manages dependencies and scripts for your project.

Now, let’s install TypeScript as a development dependency and create a configuration file:

Next, add the following configuration to your tsconfig.json file:

Optionally add the following lines for JavaScript support in a TypeScript project:

If we are fully committing to ESM, add this to the package.json :

Create a src folder and an index.ts file inside it:

Now, add a simple TypeScript script in src/index.ts :

This will serve as our starting point to ensure everything is working correctly.

To run TypeScript files directly without compiling them first, install tsx which is a popular TypeScript runner. An alternative would be to use ts-node :

You can also use type stripping natively in Node.js, but tsx fully supports TypeScript features. Now, update your package.json scripts to use tsx :

Let’s break down what each script does:

For automatic reloading, update the dev script:

The --watch flag makes tsx automatically recompile and reload files when changes are made.

Many applications require sensitive API keys and environment variables. The best practice is to store them in a .env file instead of hardcoding them. Create a .env file in your project directory with the following content:

Then, modify src/index.ts to read the environment variable:

To ensure environment variables are recognized by TypeScript, install Node.js type definitions:

If you’re using Node.js 20.6.0 or newer, you can load environment variables directly using the --env-file flag:

For a more sophisticated approach, consider using the dotenv package:

Modify src/index.ts to load the .env file using dotenv :

Update the package.json scripts accordingly:

Now, your project can securely read environment variables.

That’s it! You’ve successfully set up a TypeScript project with Node.js. Here’s a quick recap of what we did:

Now you’re ready to start building your TypeScript-powered Node.js application!

Recommended articles