“TypeScript” is the superset of JavaScript that implies all of its functionalities including the new ones. It is mostly used to enhance the development process by the addition of external libraries and packages. It performs all these tasks by transforming the code into JavaScript that can be run in any environment like NodeJS, browser, express, and many others.
However, the TypeScript code can be directly run using the “ts-node”. The “ts-node” is the TypeScript engine that directly executes the TypeScript code without transpiling it into JavaScript. It is mostly used for saving the extra time that consumes while transforming the large TypeScript code into JavaScript code.
This post will explain the complete procedure for running TypeScript in Node.js using ts-node.
How to Run TypeScript in Node.js Using ts-node?
To run TypeScript in Node.js using “ts-node”, follow the given steps
Step 1: Create Node.js Project
First, create a Node.js project with TypeScript that must have the following folder structure:
Step 2: Install “ts-node” Package
Next, open the terminal of VS code using the “Ctrl+Shift+`” key, and install the “typescript” and the “ts-node” in the project by executing the following “npm(Node Package Manager)” command:
TypeScript and “ts-node” have been added successfully to the current project.
For more verification, check the version of the “ts-node” with the help of the below-stated command:
It can be seen that the “ts-node” with version “v10.9.1” has been successfully installed in the current project.
Step 3: Create “.ts” Extension File
Next, create a “.ts” extension and type the following one-line code in it:
The above line of code applies the “console.log()” method to display the given statement as an output:
Press “Ctrl+S” to save the file.
Step 4: Execute the “.ts” File Using “ts-node”
Now, run the “.ts” file with the help of the “ts-node” that will directly compile the TypeScript file without converting it into the JavaScript file:
It can be observed that the output executes the “.ts” file successfully.
That’s all about running the TypeScript in Node.js using ts-node.
Conclusion
To run/execute the TypeScript in Node.js using “ts-node”, first, install the “TypeScript” and “ts-node” in your Node.js project. Next, create a “.ts” extension file and write some code into it. After that, execute the “.ts” file with the help of the “ts-node”. It will convert the “.ts” file into “.js” in memory without writing it in the project. This post has practically explained the complete procedure to run TypeScript in Node.js using ts-node.