全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-21 7 分钟 ✍️ juanwangdev

TypeScript 安装与配置

TypeScript 的安装与配置是开发的第一步,下面梳理核心步骤。

TypeScript 安装

npm 全局安装

Bash
npm install -g typescript

安装完成后验证:

Bash
tsc --version
# 输出示例:Version 5.4.5

项目本地安装

Bash
npm init -y
npm install typescript --save-dev

本地安装后通过 npx 调用:

Bash
npx tsc --version

版本管理

指定版本安装:

Bash
npm install -g typescript@5.3.3

tsconfig.json 配置

初始化配置

Bash
tsc --init

生成默认配置文件:

JSON
{
  "compilerOptions": {
    "target": "ES2016",
    "module": "commonjs",
    "strict": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "esModuleInterop": true
  }
}

核心编译选项

选项说明常用值
target编译目标 JavaScript 版本ES5/ES2015/ES2020/ESNext
module模块系统类型commonjs/es2015/esnext/node16
outDir输出目录./dist/./build
rootDir源码根目录./src
strict启用所有严格类型检查选项true/false
esModuleInterop兼容 CommonJS 模块导入true/false

常用配置示例

JSON
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist", "**/*.test.ts"]
}

注意:skipLibCheck 跳过声明文件类型检查,可显著提升编译速度;declaration 生成 .d.ts 文件供其他项目使用。

编译命令

Bash
# 编译整个项目
tsc

# 监听模式(文件变化时自动编译)
tsc --watch

# 指定配置文件
tsc --project tsconfig.prod.json

要点总结

  • 全局安装 typescript 提供 tsc 命令,本地安装作为项目依赖更可控
  • tsconfig.jsontarget 决定输出 JS 版本,module 决定模块系统
  • strict: true 启用严格模式,推荐生产项目开启
  • outDirrootDir 分离源码与编译产物,保持项目结构清晰

📝 发现内容有误?点击此处直接编辑

← 上一篇 TypeScript 模块系统
下一篇 → VS Code 与 TypeScript 集成
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库