TypeScript 环境搭建
TypeScript 的运行依赖 Node.js,整体流程只需四步:
安装 Node.js → 安装 TypeScript → 创建 tsconfig.json → 编译 / 运行
安装 Node.js
TypeScript 的编译工具 tsc 基于 Node.js 运行,请先确保已安装 Node.js 16.0 及以上版本。
node -v # 确认安装
npm -v # 确认 npm 可用
如果命令不存在,说明还没有安装 Node.js,参考 Node.js 环境搭建 完成安装后,再次运行上述命令确认。
安装 TypeScript
实际项目中几乎都使用本地安装,即把 TypeScript 作为项目的开发依赖,锁定版本,保证团队环境一致。
# 如果项目还没有 package.json,先初始化
npm init -y
# 安装 TypeScript 为开发依赖
npm install typescript --save-dev
安装后,所有 tsc 命令都通过 npx 调用(例如 npx tsc --version),无需全局安装。
创建 tsconfig.json 配置文件
使用 tsc --init 生成配置文件,然后只保留几个核心选项即可(多余配置可删除或注释):
npx tsc --init
修改 tsconfig.json 为最小可用配置:
{
"compilerOptions": {
"target": "ES2020", // 编译后的 JS 版本
"module": "commonjs", // Node.js 常用模块格式
"strict": true, // 开启严格类型检查(强烈推荐)
"outDir": "./dist", // 编译输出目录
"esModuleInterop": true, // 兼容 ES Module 与 CommonJS
"skipLibCheck": true // 跳过依赖库类型检查,提速
},
"include": ["src/**/*"], // 编译 src 目录下的所有文件
"exclude": ["node_modules"] // 排除依赖目录
}
将 .ts 源文件统一放在 src/ 目录下,编译后会在 dist/ 生成对应的 .js 文件。
编译和运行 TypeScript
方式一:编译后运行(最标准)
- 在
src/下创建hello.ts:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("TypeScript"));
- 执行编译:
npx tsc # 根据 tsconfig.json 编译全部文件
# 或指定单个文件
npx tsc src/hello.ts
- 运行产物:
node dist/hello.js
# 输出:Hello, TypeScript!
方式二:直接运行 .ts(开发调试推荐)
开发阶段反复编译较慢,推荐使用 tsx(基于 esbuild,速度极快)直接执行 .ts 文件,无需手动编译:
npm install tsx --save-dev
# 直接运行
npx tsx src/hello.ts
# 输出:Hello, TypeScript!
提示:tsx 仅适用于开发调试,生产部署仍建议先编译成 JS 再运行。
常用命令速查
| 命令 | 用途 |
|---|---|
npm install typescript --save-dev |
本地安装 TypeScript |
npx tsc --init |
生成 tsconfig.json |
npx tsc |
编译项目(依据 tsconfig) |
npx tsc --watch |
监听文件变动自动编译 |
npx tsx <文件> |
直接运行 .ts 文件(推荐) |
至此,你已经拥有了一个可用的 TypeScript 开发环境,可以开始编写和运行 TypeScript 代码了。