搭建最基础的 TS 开发环境

404 阅读2分钟

「这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战

上一篇介绍了mac终端命令如何创建和编译ts文件,这一篇就是通过mac终端命令搭建最基础的TS开发环境,也会介绍tsconfig.json文件的相关配置

开发环境搭建

// 1. 创建文件夹,创建package.json文件
mkdir tsdemo
cd tsdemo
npm init -y // add package.json
// 2. 生成tsconfig.json文件
tsc -init
// 3. 新建src和build文件夹,新建index.html文件
mkdir src
mkdir build
touch index.html
// 4. src下新建page.ts文件
cd src
touch page.ts
// 5. 配置tsconfig.json文件,修改outDir和rootDir
open tsconfig.json
"rootDir": "./src" /* ts文件位置目录 */
"outDir": "./build", /* 编译后js文件存放目录 */
// 6. 编写index.html
open index.html // 打开文件,添加如下内容
// 7. 编写page.ts文件
open page.ts // 打开文件,添加输出 console.log('hello world!')
tsc // 转译文件,生成build/page.js文件
// 8. 浏览器中查看index.html文件
// 控制台会输出 “hello world!”

index.html文件内容

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="./build/page.js"></script>
    <title>Document</title>
  </head>
  <body></body>
</html>

搭建效果展示:

ic_tsc_3.png

配置文件介绍

编译配置文件tsconfig.json的详细配置介绍文档:www.tslang.cn/docs/handbo…

注意:配置文件不支持单引号,里面必须使用双引号

常用配置:

{
 // "include": ["demo1.ts"], // 指定要编译的文件,包含文件
 // "exclude": ["demo2.ts"], // 不包含的文件
 // "files":["demo1.ts"], // 配置效果和include几乎一样
 "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    "removeComments": true, /* 去除注释 */
    "strict": true, /* 严格模式 编译和书写规范 */
    "noImplicitAny": false, /* 允许注解类型any不用特意表明。为true代表any值也需要类型注释,不然报错 */
    "strictNullChecks": false, /* 不强制检查 NULL 类型 */
    // "outFile": "./build/page.js", // 多文件编译成一个文件,定义该文件输出
    // "module": "amd", // 与outFile结合使用
    "outDir": "./build", // 编译后js文件存放目录
    // "rootDir": "./src", // ts文件位置目录
    "target":"es5" ,  // 默认是开启的,必须开启才能转换成功(es6语法转为es5语法),和allowJs连用
    "allowJs":true,   // 两项都开启后,在使用tsc编译时,就会编译js文件了
    "sourceMap": true, /* 位置信息文件 */
    "noUnusedLocals": true, /* 无用代码提示,避免无用代码编译,减少资源浪费 */
    "noUnusedParameters": true, /* 无用函数提示 */
  }
}

使用命令:

tsc --init // 生成tsconfig.json编译配置文件
tsc demo1.ts // ts文件编译为js文件,但tsconfig.json未生效
tsc // 直接运行该命令,tsconfig.json生效了
tsc -w // 监视,只要有更新就会重新编译

运行效果:

截屏2021-11-15 下午3.42.36.png