乐闻世界logo
搜索文章和话题

How to run TypeScript files from command line?

4个答案

1
2
3
4

Running TypeScript files via the command line requires several steps. I will walk you through the process step by step.

Step 1: Install Node.js

Ensure that your computer has Node.js installed. Node.js is a JavaScript runtime that enables you to run JavaScript code on the server side. If you haven't installed Node.js yet, visit the official website to download and install it:

Node.js official website

Step 2: Install TypeScript

Install the TypeScript compiler via the command line. Installing TypeScript globally using npm ensures that the ts-node command is available anywhere.

shell
npm install -g typescript

Step 3: Install ts-node

ts-node is a tool that executes TypeScript files and runs them directly in the Node.js environment. It automatically compiles TypeScript code into JavaScript in the background and executes the converted code immediately.

shell
npm install -g ts-node

Step 4: Write TypeScript Code

Create a new TypeScript file in your preferred text editor, such as example.ts, and write TypeScript code. For example:

typescript
// example.ts function greet(person: string) { return "Hello, " + person + "!"; } console.log(greet("world")); // Output: Hello, world!

Step 5: Run the TypeScript File

Open the command line tool, navigate to the directory containing the example.ts file, and run it using the following command:

shell
ts-node example.ts

Sample Output:

plain
Hello, world!

ts-node automatically compiles the example.ts file into JavaScript and executes it in the Node.js environment.

This completes the steps to run TypeScript files via the command line.

2024年6月29日 12:07 回复

Building on @Aamod's answer, if you want to compile and run your code with a single command, you can use the following commands:

Windows: tsc main.ts | node main.js

Linux / macOS: tsc main.ts && node main.js

2024年6月29日 12:07 回复

We have the following steps:

  1. First, you need to install TypeScript

    shell
    npm install -g typescript
  2. Create a file named helloworld.ts

    shell
    function hello(person){ return "Hello, " + person; } let user = "Aamod Tiwari"; const result = hello(user); console.log("Result", result)
  3. Open the command prompt and type the following command

    shell
    tsc helloworld.ts
  4. Run the command again

    shell
    node helloworld.js
  5. The result will be displayed in the console

2024年6月29日 12:07 回复

Run the following command to globally install the required packages:

bash
npm install -g ts-node typescript '@types/node'

Next, run the following command to execute the TypeScript file:

bash
ts-node typescript-file.ts
2024年6月29日 12:07 回复

你的答案