tsc 命令 #

1. 概述 #

tsc(TypeScript Compiler)是 TypeScript 官方提供的命令行编译器,用于将 TypeScript 代码编译为 JavaScript 代码。它提供了丰富的选项来控制编译过程,支持多种输出格式和目标环境。

2. 安装 #

要使用 tsc,首先需要安装 TypeScript:

bash
npm install -g typescript  # 全局安装
npm install --save-dev typescript  # 项目本地安装

安装完成后,可以通过以下命令验证安装:

bash
tsc --version

3. 基本用法 #

3.1 编译单个文件 #

bash
tsc hello.ts

这会将 hello.ts 编译为 hello.js

3.2 编译多个文件 #

bash
tsc file1.ts file2.ts file3.ts

3.3 编译整个目录 #

bash
tsc src/*.ts

3.4 监听模式 #

在监听模式下,tsc 会监视源文件的变化并自动重新编译:

bash
tsc --watch

4. 常用编译选项 #

4.1 输出配置 #

选项 描述 示例
--outDir 指定输出目录 tsc --outDir dist
--outFile 将所有输入文件合并为一个输出文件 tsc --outFile bundle.js
--rootDir 指定根目录,用于计算输出文件的相对路径 tsc --rootDir src --outDir dist
--noEmit 不生成输出文件(仅进行类型检查) tsc --noEmit
--emitDeclarationOnly 仅生成声明文件(.d.ts) tsc --emitDeclarationOnly

4.2 目标环境 #

选项 描述 示例
--target 指定 ECMAScript 目标版本 tsc --target ES2020
--module 指定模块系统 tsc --module CommonJS
--lib 指定要包含的库文件 tsc --lib ES2020,DOM
--moduleResolution 指定模块解析策略 tsc --moduleResolution node
--esModuleInterop 启用 ES 模块互操作性 tsc --esModuleInterop

4.3 类型检查 #

选项 描述 示例
--strict 启用所有严格类型检查选项 tsc --strict
--noImplicitAny 禁止隐式 any 类型 tsc --noImplicitAny
--strictNullChecks 启用严格的 null 检查 tsc --strictNullChecks
--strictFunctionTypes 启用严格的函数类型检查 tsc --strictFunctionTypes
--strictBindCallApply 启用严格的 bind/call/apply 检查 tsc --strictBindCallApply
--strictPropertyInitialization 启用严格的属性初始化检查 tsc --strictPropertyInitialization
--noImplicitThis 禁止隐式 this 类型 tsc --noImplicitThis
--alwaysStrict 在输出文件中添加 “use strict” tsc --alwaysStrict

4.4 代码质量 #

选项 描述 示例
--noUnusedLocals 禁止未使用的局部变量 tsc --noUnusedLocals
--noUnusedParameters 禁止未使用的参数 tsc --noUnusedParameters
--noFallthroughCasesInSwitch 禁止 switch 语句中的贯穿情况 tsc --noFallthroughCasesInSwitch
--noImplicitReturns 禁止函数中隐式返回 tsc --noImplicitReturns

5. tsconfig.json 配置文件 #

使用配置文件可以更方便地管理编译选项。默认情况下,tsc 会在当前目录查找 tsconfig.json 文件。

5.1 创建配置文件 #

bash
tsc --init

5.2 配置文件示例 #

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "CommonJS",
    "lib": ["ES2020", "DOM"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

5.3 常用配置选项 #

  • compilerOptions: 编译选项的集合
  • include: 要包含的文件/目录
  • exclude: 要排除的文件/目录
  • extends: 继承其他配置文件
  • files: 指定要编译的文件列表

6. 高级用法 #

6.1 使用装饰器 #

bash
tsc --experimentalDecorators --emitDecoratorMetadata

6.2 生成 source map #

bash
tsc --sourceMap

6.3 声明文件生成 #

bash
tsc --declaration

6.4 增量编译 #

bash
tsc --incremental

7. 常见问题 #

7.1 编译错误 #

  • 问题: 编译时出现 “Cannot find name ‘Promise’” 解决: 添加 --lib ES2015 选项

  • 问题: 模块导入错误 解决: 检查 modulemoduleResolution 配置

7.2 性能优化 #

  • 使用增量编译 (--incremental)
  • 合理配置 includeexclude
  • 使用 --skipLibCheck 跳过库文件检查

8. 总结 #

tsc 是 TypeScript 开发中不可或缺的工具,它提供了强大的编译和类型检查功能。通过合理配置编译选项和使用配置文件,可以灵活地适应不同的项目需求和开发环境。

最后更新:2026-02-07