安装与编译

TypeScript 教程 · 第 2 章 · 6 次浏览

TypeScript 编译器把 .ts 文件转成 .js。安装和编译都很简单。

安装

全局或项目内安装:npm install -D typescript,然后 npx tsc --init 生成 tsconfig.json。

编译

  • npx tsc:按 tsconfig 编译
  • npx tsc --watch:监听文件变化自动编译
  • 项目里一般不用 tsc 直接跑,而是用 Vite 这类工具内置的转换

tsconfig 常用项

  • target:编译目标 ES 版本
  • strict:严格模式(推荐 true)
  • outDir:输出目录
  • module:模块系统

代码示例

// tsconfig.json
{
    "compilerOptions": {
        "target": "ES2020",
        "module": "ESNext",
        "strict": true,
        "outDir": "./dist",
        "rootDir": "./src",
        "skipLibCheck": true
    },
    "include": ["src"]
}

// 命令行
// npm install -D typescript
// npx tsc --init
// npx tsc                → 编译
// npx tsc --watch        → 监听模式