How to Run Typescript Files from Command Line in node.js?
To run TypeScript files from the command line in Node.js, you need to transpile the TypeScript code to JavaScript first, and then execute the generated JavaScript file using Node.js. Here are the steps:
Install TypeScript If you haven't installed TypeScript globally, you can do so using the following command:
npm install -g typescript
Write TypeScript Code Create a TypeScript file (e.g.,
example.ts
) with your TypeScript code. For example:// example.ts const greeting: string = 'Hello, TypeScript!'; console.log(greeting);
Transpile TypeScript to JavaScript Use the
tsc
command (TypeScript Compiler) to transpile the TypeScript code into JavaScript. Run this command in the same directory as your TypeScript file:tsc example.ts
This will generate a JavaScript file (
example.js
) based on your TypeScript code.Run JavaScript File Now, you can run the generated JavaScript file using Node.js:
node example.js
This will execute the JavaScript code generated from your TypeScript file.
Optional: Use ts-node for Direct Execution without Transpilation
If you prefer to skip the separate transpilation step, you can use ts-node
to directly run TypeScript files. First, install ts-node
globally:
npm install -g ts-node
Then, you can run your TypeScript file directly:
ts-node example.ts
ts-node
internally handles the transpilation and execution of TypeScript files, making it convenient for development and scripting. However, note that it might have a slight runtime performance overhead compared to pre-transpiling your TypeScript code.