How to Run Typescript Files from Command Line in node.js?

Better Stack Team
Updated on April 4, 2024

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:

  1. Install TypeScript If you haven't installed TypeScript globally, you can do so using the following command:

     
    npm install -g typescript
    
  2. 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);
    
  3. 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.

  4. 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.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

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 us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build 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.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github