VScode搭建TypeScript开发环境

来源:互联网 发布:手机淘宝客链接转换器 编辑:程序博客网 时间:2024/06/05 13:26

  TypeScript 是 JavaScript 的类型的超集,它可以编译成纯 JavaScript。编译出来的 JavaScript 可以运行在任何浏览器上。TypeScript 编译工具可以运行在任何服务器和任何系统上,TypeScript 是开源的。为什么选择 TypeScript以及TypeScript优缺点阅读TypeScript入门教程。利用VScode搭建TypeScript开发环境前提是已经安装node.js和VScode。

1、安装TypeScript

使用npm工具安装全局TypeScript:

npm install -g typescript

2、创建helloTypeScript

创建helloTypeScript目录,在命令行cmd下进入helloTypeScript目录

cd helloTypeScript

这里写图片描述

输入:npm init,创建package.json,package.json文件如下:

{  "name": "hellotypescript",  "version": "1.0.0",  "description": "hello typescript",  "main": "index.html",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1",    "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\"",    "lite": "lite-server",    "tsc": "tsc",    "tsc:w": "tsc -w"     },  "keywords": [    "typescript"  ],  "author": "sanshui",  "license": "ISC",  "dependencies": {  },  "devDependencies": {    "lite-server": "^2.2.0",    "concurrently": "^2.0.0"  }}
  • concurrently—同时执行命令用
  • lite-server—轻量级的Node开发服务器

3、安装依赖包、编写示例代码

使用npm i 或者 cnpm i 或者yarn 安装依赖包

npm i

编写HelloTypeScript.ts代码:

class HelloTypeScript {  helloString: string;  constructor(message: string) {      this.helloString = message;  }  hello() {      return this.helloString;  }}let myName: string = 'SanShui'let myAge: number = 23let sentence: string = `Hello, my name is ${myName}. I'll be ${myAge + 1} years old next month`let helloTypeScript = new HelloTypeScript(sentence);document.body.innerHTML = helloTypeScript.hello();

index.html:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>HelloTypeScript</title></head><body>    <script src="dist/tsc.js"></script></body></html>

4、创建 tsconfig.json

  当前TypeScript代码并不能直接执行,需编译为JavaScript代码。而借助VS Code,我们就不用在命令行输入编译命令了。为此,在根目录添加一个tsconfig.json文件。该文件是TypeScript编译器配置文件。

{  "compilerOptions": {    "module": "amd",    "noImplicitAny": true,    "removeComments": true,    "preserveConstEnums": true,    "outFile": "dist/tsc.js",    "sourceMap": true  },  "include": [    "src/*"  ],  "exclude": [    "node_modules"  ]}

tsconfig.json详细配置请查看:tsconfig.json配置

5、编译运行

npm run start

编译后目录结构如图:

这里写图片描述

运行结果如图:

这里写图片描述

修改TypeScript程序,服务器会自动编译并刷新浏览器。

参考链接:
http://www.cnblogs.com/xuanhun/p/6027624.html
http://www.cnblogs.com/sunjie9606/p/5945540.html

原创粉丝点击