【TypeScript教程】03—如何使用 TypeScript 编写" Hello World "程序

16db30906aae26a0d5dc027d9444b57f.png

英文 | https://www.javascripttutorial.net

翻译 | 杨小爱

在今天的教程中,我们将学习如何使用 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 启动一个新终端。

e627ea0bc9cdeeb790f65c01381c7f0f.png

第六,在终端输入以下命令编译app.ts文件:

 
 
tsc app.ts

e65710f357cf7180c891b1ef45e2be23.png

如果一切正常,我们会看到 TypeScript 编译器生成了一个名为 app.js 的新文件:

b5134dd4c3bf09e49caf6ca3da859001.png

要在 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 选项:

9c7c7201b2330c185671cea076fb99b3.png

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

cbe8c1334ba73daa2b70ee2f6f749408.png

要进行更改,我们需要编辑 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 浏览器。

推荐阅读

【TypeScript教程】01—什么是 TypeScript?

【TypeScript教程】02—设置TypeScript

学习更多技能

请点击下方公众号

e335329bf1f2a7015d156180e0bd238b.gif

a3e07e62f51e5a3b43d67389b52fc910.png

54d5969254263c203bebb291fd6cdb37.png

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值