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.
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github