Node.js TypeScript: How to Automate the Development Workflow

Summary: in this tutorial, you’ll learn how to automate the workflow for developing Node.js applications using TypeScript.

Creating a Node.js TypeScript project

Step 1. Instal Node.js.

Step 2. Install typescript and ts-node packages globally:

npm install -g typescript ts-node

The typescript is a compiler that compiles TypeScript to JavaScript. The ts-node allows you to run a TypeScript directly on Node.js without precompiling it to JavaScript.

Step 3. Install nodemon package to monitor the changes and automatically restart the Node application.

npm install -g nodemon

Step 4. Create a new directory called nodets and navigate to the project directory:

mkdir nodets
cd nodets

Step 5. Create a package.json file:

npm init --yes

Step 6. Create a subdirectory src where you store the TypeScript code:

mkdir src

Step 7. Create a new file app.ts in the src directory.

Step 8. Create a nodemon’s configuration file:

{
  "watch": ["src"],
  "ext": ".ts,.js",
  "ignore": [],
  "exec": "ts-node ./src/app.ts"
}Code language: JSON / JSON with Comments (json)

This file instructs nodemon to watch for the code changes in the src directory with the extension ts and js and execute the ./src/app.ts file using the ts-node command.

Step 9. Change the scripts in the package.json file to the following:

"scripts": {
   "start": "nodemon"
},Code language: JSON / JSON with Comments (json)

Run the Node application

First, start the Node.js application by running the following command:

npm start

It’ll run the nodemon command specified in the package.json file, which executes the ts-node ./src/app.ts specified in the nodemon configuration file.

Second, change the source code in the app.ts file and view the result in the console.

Summary

  • Use the nodemon package to constantly restart the Node app when the source code changes.
  • Use the ts-node package to run the TypeScript files directly on Node.js without precompiling them into JavaScript files.
Was this tutorial helpful ?