TypeScript “Hello, World!”

摘要:在本教程中,您将学习如何在 TypeScript 中开发 Hello World 程序。

Node.js 中的 TypeScript Hello World 程序

首先,创建一个新目录来存储代码,例如:helloworld

其次,启动 VS Code 并打开该目录。

第三,创建一个名为 app.ts 的新 TypeScript 文件。TypeScript 文件的扩展名为 .ts

第四,在 app.ts 文件中键入以下源代码

let message: string = 'Hello, World!';
console.log(message);Code language: TypeScript (typescript)

第五,使用键盘快捷键 Ctrl+` 或通过菜单 终端 > 新建终端 在 VS Code 中启动一个新的终端

第六,在终端上键入以下命令来编译 app.ts 文件

tsc app.tsCode language: CSS (css)

如果一切正常,您将看到一个名为 app.js 的新文件由 TypeScript 编译器生成

要在 Node.js 中运行 app.js 文件,请使用以下命令

node app.jsCode language: CSS (css)

如果您安装了在设置 TypeScript 开发环境中提到的 tsx 模块,您可以使用一个命令直接在 Node.js 上运行 TypeScript 文件,而无需先将其编译为 JavaScript

tsx app.tsCode language: CSS (css)

Web 浏览器中的 TypeScript Hello World 程序

以下步骤将向您展示如何创建一个网页,该网页在 Web 浏览器上显示 Hello, World! 消息。

首先,创建一个名为 index.html 的新文件,并包含如下所示的 app.js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TypeScript: Hello, World!</title>
</head>
<body>
    <script src="app.js"></script>
</body>
</html>Code language: HTML, XML (xml)

请注意,TypeScript 编译器 (tsc) 将 app.ts 文件编译成 app.js 文件。

其次,将 app.ts 代码更改为以下内容

let message: string = 'Hello, World!';

// create a new heading 1 element
let heading = document.createElement('h1');
heading.textContent = message;

// add the heading the document
document.body.appendChild(heading);Code language: TypeScript (typescript)

第三,将 app.ts 文件编译成 app.js 文件

tsc app.tsCode language: CSS (css)

第四,通过右键单击 index.html 并选择“使用 Live Server 打开”选项,从 VS Code 中打开 Live Server

Live Server 将打开 index.html 并显示以下消息

要进行更改,您需要编辑 app.ts 文件。例如

let message: string = 'Hello, TypeScript!';

let heading = document.createElement('h1');
heading.textContent = message;

document.body.appendChild(heading);Code language: TypeScript (typescript)

并编译 app.ts 文件

tsc app.tsCode language: CSS (css)

TypeScript 编译器将生成一个新的 app.js 文件,并且 Live Server 将自动在 Web 浏览器中重新加载它。

请注意,app.jsapp.ts 文件的输出文件,因此,您永远不应该直接更改其内容,否则一旦重新编译 app.ts 文件,您将丢失更改。

在本教程中,您学习了如何在 TypeScript 中创建第一个程序,称为 Hello, World!,该程序可在 Node.js 和 Web 浏览器上运行。

本教程是否有帮助?