一、背景:
最近在学习typescript
,使用的是VScode编辑器。由于Node.js
/浏览器
只识别JS
代码,不识别TS
代码,因此需要先将TS
代码转化为JS
代码,然后就可以在Node.js
/浏览器
中运行了。
因此在使用VSCode解析TS
格式文件时,需要先下载解析工具。
二、步骤:
1、下载typescript解析
在VSCode打开终端:查看 → 终端,只需要输入以下命令(注意要联网)
npm i -g typescript //之后敲回车
出现以下情况:+版本号即为安装成功
C:\Users\acer\AppData\Roaming\npm\tsserver -> C:\Users\acer\AppData\Roaming\npm\node_modules\typescript\bin\tsserver6975f059567929.lock for C:\Users\acer\AppData\Roaming\npm\node_modules\.
C:\Users\acer\AppData\Roaming\npm\tsc -> C:\Users\acer\AppData\Roaming\npm\node_modules\typescript\bin\tsc
+ typescript@3.9.7
added 1 package from 1 contributor in 114.196s
可能出现的问题:使用npm安装包超时
长时间出现这一串东西,网络也不走。
或者长时间等待后报出ETIMEDOUT
的错误:
request to https://registry.npmjs.org/typescript failed, reason: connect ETIMEDOUT 104.16.26.35:443
This is a problem related to network connectivity.
In most cases you are behind a proxy or have bad network settings.
If you are behind a proxy, please make sure that the network 'proxy' config is set properly. See: 'npm help config'
A complete log of this run can be found in:
原因:
是因为下载的源是外国的,很慢。
解决:
使用淘宝镜像,即改变下载的源。
npm config set registry https://registry.npm.taobao.org
另外还有其他的源:
npm ---- https://registry.npmjs.org/
cnpm --- http://r.cnpmjs.org/
taobao - http://registry.npm.taobao.org/
eu ----- http://registry.npmjs.eu/
au ----- http://registry.npmjs.org.au/
sl ----- http://npm.strongloop.com/
nj ----- https://registry.nodejitsu.com/
2、新建TS文件
新建一个后缀名为.ts
的文件,在hello.ts
中写任意的js
代码:
console.log("hello world");
右键文件,在终端打开。
3、在终端中,使用TSC命令编译TS文件
tsc hello.ts
VScode会自动创建出hello.js
文件,出现该文件即代表解析成功
可能出现的问题:报错 "因为在此系统上禁止运行脚本"
PS C:\Users\acer\Desktop> tsc hello.ts
tsc : 无法加载文件 C:\Users\acer\AppData\Roaming\npm\tsc.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅
https:/go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies。
所在位置 行:1 字符: 1
1. tsc hello.ts
2. ~~~
+ CategoryInfo : SecurityError: (:) [],PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
PS C:\Users\acer\Desktop> set-executionpolicy remotesigned
解决:
- 以管理员身份运行vscode(敲重点!!!);
- 执行:
get-ExecutionPolicy
,显示Restricted
,表示状态是禁止的;- 执行:
set-ExecutionPolicy RemoteSigned
;
执行策略更改
执行策略可帮助你防止执行不信任的脚本。更改执行策略可能会产生安全风险,如
https:/go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies 帮助主题所述。是否要更改执行策略?
[Y] 是(Y) [A] 全是(A) [N] 否(N) [L] 全否(L) [S] 暂停(S) [?] 帮助 (默认值为“N”): y
set-executionpolicy : 对注册表项“HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerSh
ell”的访问被拒绝。 要更改默认(LocalMachine)作用域的执行策略,请使用“以管理员身份运行”选项启动 Windows PowerS
hell。要更改当前用户的执行策略,请运行 "Set-ExecutionPolicy -Scope CurrentUser"。
所在位置 行:1 字符: 1
+ set-executionpolicy remotesigned
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPol
icyCommand
- 这时再执行
get-ExecutionPolicy
,就显示RemoteSigned
;
4、可以在node中运行.ts
文件
node hello.ts
结果如下: