第一次运行 TypeScript
1, 创建文件夹并初始化项目
- mkdir ts-demo
- cd ts-demo
- NPM init -y
2, 安装 typescript 与 ts-node
- # 局部安装
- NPM install -d typescript
- NPM install -d ts-node
- # 全局安装
- NPM install -g typescript
- NPM install -g ts-node
3, 创建 ts 文件, 并添加代码
- touch demo.ts
- echo "console.log('hello typescript')">>demo.ts
4, 创建. vscode/launch.JSON 文件
- mkdir .vscode
- cd .vscode
- touch launch.JSON
5, 给 launch.JSON 文件添加如下代码
- {
- "configurations": [{
- "name": "ts-node",
- "type": "node",
- "request": "launch",
- "program": "${workspaceRoot}/node_modules/ts-node/dist/bin.js",
- "args": ["${relativeFile}"],
- "cwd": "${workspaceRoot}",
- "protocol": "inspector"
- }]
- }
此时的目录结构为:
6, 调试并运行
在 VScode 编辑器中中点击 Ctrl+Shift+D 进入调试页面.
选中 demo.ts 文件, 然后点击开始调试即可.
tsc 的使用
我们先重新更改下 demo.ts 文件内容
- function greeter(person: string) {
- return "Hello," + person;
- }
- let user = "Jane User";
- console.log(greeter(user));
在命令行里使用如下命令进行编译
./node_modules/typescript/bin/tsc demo.ts
我们就可以看到新生成了一个 JS 文件!
如果我们再更改下 ts 文件
- function greeter(person: string) {
- return "Hello," + person;
- }
- let user = [1, 2, 3]
- console.log(greeter(user));
重新编译, 我们将会看到如下错误:
demo.ts(7,21): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.
参考文档
- https://github.com/Microsoft/TypeScript
- https://github.com/TypeStrong/ts-node
来源: http://www.bubuko.com/infodetail-3336990.html