黄子涵学习Typescript
本地编写并运行Typescript
查看Node.js版本号

全局安装Typescript

验证Typescript是否安装成功

新建tsconfig.json文件
使用新建文件快捷键“Ctrl + N”来创建一个文件并输入以下代码
{
"compilerOptions": {
"strict": true,
"target": "es5"
}
}
使用保存文件快捷键“Ctrl + S”将这个文件保存为“tsconfig.json”。“tsconfig.json”是TypeScript编译器默认使用的配置文件。此例中的配置文件启用了所有的严格类型检查编译选项,并将输出JavaScript的版本指定为ECMAScript 5。

新建hello-world.ts文件
使用新建文件快捷键“Ctrl + N”来创建一个文件并输入以下代码
const greeting = 'hello, world';
console.log(greeting);
使用保存文件快捷键“Ctrl + S”将这个文件保存为“hello-world.ts”,TypeScript源文件的常规扩展名为“.ts”。

编译程序
Visual Studio Code的任务管理器已经集成了对TypeScript编译器的支持,我们可以利用它来编译TypeScript程序。使用Visual Studio Code任务管理器的另一个优点是它能将编译过程中遇到的错误和警告信息显示在“Problems”面板里。
使用快捷键“Ctrl + Shift + B”或从菜单栏里选择“Terminal→Run Build Task”来打开并运行构建任务面板,然后再选择“tsc: build- tsconfig.json”来编译TypeScript程序。
当编译完成后,在“hello-world.ts”文件的目录下会生成一个同名的“hello-world.js”文件,它就是编译输出的JavaScript程序。


生成的“hello-world.js”文件如下所示:
"use strict";
var greeting = 'hello, world';
console.log(greeting);
运行程序
在Visual Studio Code里,使用“Ctrl +
”(“
”为反引号,位于键盘上数字键1的左侧)快捷键打开命令行窗口。然后,使用Node.js命令行工具来运行“hello-world.js”,示例如下:

网友评论