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

How to run TypeScript files from command line?

7 个月前提问
3 个月前修改
浏览次数146

6个答案

1
2
3
4
5
6

在命令行运行 TypeScript 文件需要几个步骤,我将一步一步详细解释这个过程。

第1步:安装Node.js

确保您的计算机上安装了Node.js。Node.js是一个JavaScript运行时,可以让您在服务器端运行JavaScript代码。如果您还没有安装Node.js,请前往官网下载并安装:

Node.js官网

第2步:安装TypeScript

通过命令行安装TypeScript编译器。使用npm(Node.js的包管理器)全局安装TypeScript可以使 ts-node命令在任何位置都可以使用。

shell
npm install -g typescript

第3步:安装ts-node

ts-node是一个可以执行TypeScript文件并将它们直接在Node.js环境中运行的工具。它会在后台自动地调用TypeScript编译器将TypeScript代码转换成JavaScript代码,并立即执行转换后的代码。

shell
npm install -g ts-node

第4步:编写TypeScript代码

在您喜欢的文本编辑器中创建一个新的TypeScript文件,例如 example.ts,并写入TypeScript代码。例如:

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

第5步:运行TypeScript文件

打开命令行工具,导航到包含 example.ts文件的目录,然后使用以下命令运行它:

shell
ts-node example.ts

示例输出:

plain
Hello, world!

ts-node会自动编译 example.ts文件到JavaScript,并在Node.js环境中执行。

以上就是在命令行中运行TypeScript文件的步骤。

2024年6月29日 12:07 回复

我如何使用 Typescript 做同样的事情

您可以tsc使用以下命令在监视模式下运行tsc -w -p .,它将.js以实时方式为您生成文件,因此您可以node foo.js像平常一样运行

传输流节点

有 ts-node : https: //github.com/TypeStrong/ts-node它将动态编译代码并通过节点运行它 🌹

shell
npx ts-node src/foo.ts
2024年6月29日 12:07 回复

运行以下命令并全局安装所需的包:

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

现在运行以下命令来执行打字稿文件:

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

我们有以下步骤:

  1. 首先你需要安装打字稿

    shell
    npm install -g typescript
  2. 创建一个文件 helloworld.ts

    shell
    function hello(person){ return "Hello, " + person; } let user = "Aamod Tiwari"; const result = hello(user); console.log("Result", result)
  3. 打开命令提示符并键入以下命令

    shell
    tsc helloworld.ts
  4. 再次运行命令

    shell
    node helloworld.js
  5. 结果将显示在控制台上

2024年6月29日 12:07 回复

你也可以试试tsx。tsx 是一个用于无缝运行 TypeScript 的 CLI 命令(替代 Node),它基于 esbuild 构建,因此速度非常快。

https://github.com/esbuild-kit/tsx

例子:

shell
npx tsx ./script.ts
2024年6月29日 12:07 回复

要添加到上面的 @Aamod 答案,如果您想使用一个命令行来编译和运行代码,您可以使用以下命令:

视窗:

shell
tsc main.ts | node main.js

Linux / macOS:

shell
tsc main.ts && node main.js
2024年6月29日 12:07 回复

你的答案