如何使用 TypeScript 编写“ Hello World “程序

在今天的教程中,我们将学习如何使用 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 elementlet heading = document.createElement('h1');heading.textContent = message;// add the heading the documentdocument.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 浏览器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cheng-Dashi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值