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!