在今天的教程中,我们将学习如何使用 TypeScript 编写 第一个“Hello World” 程序。
node.js 中的 TypeScript Hello World 程序
首先,创建一个新文件夹来存储代码,例如,helloworld。
其次,启动 VS Code 并打开该文件夹。
第三,创建一个名为app.ts。TypeScript 文件的扩展名是.ts。
第四、在app.ts文件中输入以下源代码:
let message: string = 'Hello, World!';
console.log(message);
第五,在 VS Code 中,使用快捷键 Ctrl+` 或按照菜单 Terminal > New Terminal 启动一个新终端。
第六,在终端输入以下命令编译app.ts文件:
tsc app.ts
如果一切正常,我们会看到 TypeScript 编译器生成了一个名为 app.js 的新文件:
要在 node.js 中运行 app.js 文件,请使用以下命令:
node app.js
如果我们安装了设置 TypeScript 开发环境中提到的 ts-node 模块,则只需一条命令即可编译 TypeScript 文件并一键执行输出文件:
ts-node app.ts
Web 浏览器中的 TypeScript Hello World 程序
我们按照以下步骤创建一个显示 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>
其次,将 app.js 代码更改为以下内容:
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);
第三、编译app.ts文件:
tsc app.ts
第四,通过鼠标右键单击 index.html 从 VS 代码打开 Live Server 并选择 Open with 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);
并编译 app.ts 文件:
tsc app.ts
TypeScript 编译器会生成一个新的 app.js 文件,Live Server 会自动在 Web 浏览器上重新加载它。
请注意,app.js 是 app.ts 文件的输出文件,因此,我们不应直接更改此文件中的代码,否则一旦重新编译 app.ts 文件,我们将丢失所做的更改。
在今天的教程中,我们学习了如何在 TypeScript 中创建第一个名为 Hello, World! 的程序。适用于 node.js 和 Web 浏览器。