TypeScript:TS文件转JS文件

一、ts安装

安装ts

npm install -g typescript

检测版本

tsc -v

二、ts 手动编译成 js

1. 新建 ts 文件夹,使用 vscode 打开,新建 index.ts,代码如下

(() => {
  const username: string = "小明";
  console.log(username);
})();

2. 打开控制台执行 tsc index.ts 自动生成 index.js,代码如下

(function () {
    var username = "小明";
    console.log(username);
})();

⚠️注意:测试代码要放入 ()() 立即执行函数里,否则执行 tsc index.ts 后 ts 文件变量飘红

3. tsc 的基本用法如下。

# 使用 tsconfig.json 的配置
$ tsc

# 只编译 index.ts
$ tsc index.ts

# 编译 src 目录的所有 .ts 文件
$ tsc src/*.ts

# 指定编译配置文件
$ tsc --project tsconfig.production.json

# 只生成类型声明文件,不编译出 JS 文件
$ tsc index.js --declaration --emitDeclarationOnly

# 多个 TS 文件编译成单个 JS 文件
$ tsc app.ts util.ts --target esnext --outfile index.js

三、ts 自动编译成 js

1.生成 tsconfig.json 配置文件

新建 ts 文件夹,使用 vscode 打开,终端执行

tsc --init

2.修改 tsconfig.json 配置文件

创建tsconfig.json文件,然后根据自己的需要进行修改,比如输入输出目录,包含的库等等。

{
  // 编译选项
  "compilerOptions": {
    // 生成代码的语言版本:将我们写的 TS 代码编译成哪个版本的 JS 代码
    // 命令行: tsc --target es5 11-测试TS配置文件.ts
    "target": "es5",
    // ts内置的库
    // 如果删除了dom库,则无法使用document.getElementById
    "lib": ["dom", "dom.iterable", "esnext"],
    // 允许 ts 编译器编译 js 文件
    // 允许 import js文件
    "allowJs": true,
    // 跳过类型声明文件的类型检查
    "skipLibCheck": true,
    // es 模块 互操作,屏蔽 ESModule 和 CommonJS 之间的差异
    "esModuleInterop": true,
    // 即使模块没有显式指定 default 导出,也允许通过 import x from 'y' 
    "allowSyntheticDefaultImports": true,
    // 开启严格模式
    "strict": true,
    // 对文件名称强制区分大小写  Demo.ts  
    "forceConsistentCasingInFileNames": true,
    // 为 switch 语句启用错误报告
    // 如果switch中没有break 或者 return 就报错
    "noFallthroughCasesInSwitch": true,
    // 生成代码的模块化标准
    "module": "esnext",
    // 模块解析(查找)策略
    "moduleResolution": "node",
    // 允许导入扩展名为.json的模块
    "resolveJsonModule": true,
    // 是否将没有 import/export 的文件视为旧(全局而非模块化)脚本文件
    "isolatedModules": true,
    // 编译时不生成任何文件(只进行类型检查)
    "noEmit": true,
    // 指定将 JSX 编译成什么形式
    "jsx": "react-jsx"
   // 指定输出目录 
    "outDir": "./dist",     
    // 指定输出文件目录(用于输出),用于控制输出目录结构
    "rootDir": "./src",
 }, 
  "include": ["./src/**/*"], 
  "exclude": [ "node_modules", "library", "local", "temp", "build", "settings" ], 
}

3.用watch来动态检测ts文件的改变并自动编译

tsc -w  

执行上述文件后我们可以发现进入了watch模式, 当我们在该模式下,对src中的ts文件进行了修改并保存,其会自动执行tsc命令更新.ts文件对应的.js文件,如果有报错也会在命令行中显示。

posted on 2024-03-24 23:02  梁飞宇  阅读(4618)  评论(1)    收藏  举报