【TypeScript】建立简单的运行环境

465 阅读1分钟

目的:方便学习和实践的时候,查看简单代码的输出结果。

简单编译 ts 文件

  1. npm install -g typescript 全局安装TypeScript

  2. 新建文件夹 Test

  3. 创建 test.ts 文件,写入

const str: string = '12';
  1. 创建 tsconfig.json 文件,不需要写入内容

综上文件夹结构为:

- Test
    - test.ts
    - tsconfig.json
  1. 打开终端,输入 tsc test.ts,运行文件进行编译 输出编译成功结果:

image.png

文件内容改成 const str: string = 1, 输出编译错误结果:

image.png

在浏览器打开并输出打印

在上一部分的基础上操作:

  1. 修改文件夹结构为
- Test
    - src
        - index.html
        - index.ts
    - tsconfig.json
  1. tsconfig.json 文件写入:
{
    "compilerOptions": {
        "outFile": "./build/page.js", /* 仅生成一个文件,在index.html中引入 */
        "rootDir": "./src", /* ts文件位置目录 */
        "outDir": "./build", /* 编译后js文件存放目录 */  
    }
}
  1. index.html 文件写入:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
</body>
<!-- 引入编译的js文件 -->
<script src="../build/page.js"></script>
</html>
  1. 打开终端,输入 tsc --w,运行文件进行编译并在ts文件操作之后实时更新编译结果。
// index.ts
let tom: [string, number];
tom = ['12', 14]
console.log(tom);

编译结果:

image.png

控制台打印:['12', 14]

// index.ts
let tom: [string, number];
tom = ['12', 14, 1]
console.log(tom);

编译结果:

image.png

控制台打印:['12', 14, 1]