TypeScript (一)安装

TypeScript 安装

本文介绍 TypeScript 环境的安装。

我们需要使用到 npm 工具安装,如果你还不了解 npm,可以参考我们的NPM 使用介绍。

一、NPM 安装 TypeScript

如果你的本地环境已经安装了 npm 工具,可以使用以下命令来安装。

使用国内镜像:

npm config set registry https://registry.npmmirror.com

安装 typescript:

npm install -g typescript

安装完成后我们可以使用 tsc 命令来执行 TypeScript 的相关代码,以下是查看版本号:

$ tsc -v
Version 3.2.2

在这里插入图片描述
安装时出现如下错误

npm ERR! code EPERM
npm ERR! syscall mkdir
npm ERR! path C:\Program Files\nodejs\node_modules\.staging
npm ERR! errno -4048
npm ERR! Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging'
npm ERR!  [OperationalError: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging'] {
npm ERR!   cause: [Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\.staging'] {
npm ERR!     errno: -4048,
npm ERR!     code: 'EPERM',
npm ERR!     syscall: 'mkdir',
npm ERR!     path: 'C:\\Program Files\\nodejs\\node_modules\\.staging'
npm ERR!   },
npm ERR!   stack: "Error: EPERM: operation not permitted, mkdir 'C:\\Program Files\\nodejs\\node_modules\\.staging'",
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'mkdir',
npm ERR!   path: 'C:\\Program Files\\nodejs\\node_modules\\.staging'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It's possible that the file was already in use (by a text editor or antivirus),
npm ERR! or that you lack permissions to access it.
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\danke\AppData\Roaming\npm-cache\_logs\2022-01-05T02_42_57_609Z-debug.log
重点是:`operation not permitted`  想到应该是windows系统下的权限错误。


解决方法:   使用win+x,选择命令提示符(管理员),在里面运行命令就好了。

在这里插入图片描述
然后我们新建一个 app.ts 的文件,代码如下:

var message:string = "Hello World" 
console.log(message)

通常我们使用 .ts 作为 TypeScript 代码文件的扩展名。

然后执行以下命令将 TypeScript 转换为 JavaScript 代码:

tsc app.ts

在这里插入图片描述

在这里插入图片描述
这时候在当前目录下(与 app.ts 同一目录)就会生成一个 app.js 文件,代码如下:

var message = "Hello World";
console.log(message);

在这里插入图片描述

使用 node 命令来执行 app.js 文件:

$ node app.js 
Hello World

在这里插入图片描述

TypeScript 转换为 JavaScript 过程如下图:
在这里插入图片描述

二、Visual Studio Code

我们可以在左侧窗口中点击当前编辑的代码文件,选择 open in command prompt(在终端中打开),这时候我们就可以在屏幕的右侧下半部分使用 tsc 命令来执行 TypeScript 文件代码了。
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值