环境配置
本地环境
.ts 文件不能直接在浏览器或 Node.js 中运行,需要先编译为 .js。通常建议在项目内安装编译器并通过脚本调用,保证多人协作和 CI 使用一致的版本。
tsc 的安装与使用
tsc 是 typescript compiler 的缩写,即 TypeScript 的编译器。
安装 TypeScript
# 使用 pnpm 安装(推荐)
pnpm add -D typescript
# 或使用 npm
npm install -D typescript
# 或使用 yarn
yarn add -D typescript
bash
初始化配置
# 生成 tsconfig.json 配置文件
npx tsc --init
# 查看编译器版本
npx tsc -v
# 示例输出:Version 5.7.2(2026 年 1 月最新版本)
bash
编译 TypeScript
# 编译单个文件
npx tsc demo.ts && node demo.js
# 编译整个项目(受 tsconfig 包含规则控制)
npx tsc
# 监听模式(文件变化时自动重新编译)
npx tsc --watch
bash
💡 建议:在
package.json中封装脚本,避免依赖全局安装:{ "scripts": { "build:ts": "tsc -p tsconfig.json", "dev": "tsc --watch" } }json
运行时工具
如果你希望直接运行 TypeScript 文件(脚本或开发调试),可以使用以下运行时工具:
tsx(推荐,2026 年主流)
特点:
- ⚡️ 极快的启动速度(比 ts-node 快 20-30 倍)
- 🔧 零配置,开箱即用
- 📦 支持 ESM 和 CommonJS
- 🎯 完美支持 TypeScript 5.x/6.x
# 安装
pnpm add -D tsx
# 运行 TypeScript 文件
npx tsx demo.ts
# 监听模式
npx tsx watch demo.ts
# 在 package.json 中配置
{
"scripts": {
"dev": "tsx watch src/index.ts",
"start": "tsx src/index.ts"
}
}
bash
ts-node
特点:
- 📚 成熟稳定,社区广泛使用
- 🔧 配置选项丰富
- 🎯 适合复杂项目配置
# 安装
pnpm add -D ts-node
# 运行 TypeScript 文件
npx ts-node demo.ts
# 在 package.json 中配置
{
"scripts": {
"dev": "ts-node src/index.ts"
}
}
bash
工具对比(2026 年)
| 特性 | tsx | ts-node |
|---|---|---|
| 启动速度 | ⚡️ 极快(20-30x) | 🐌 较慢(1x) |
| 配置复杂度 | ✅ 零配置 | ⚠️ 需要配置 |
| ESM 支持 | ✅ 原生支持 | ⚠️ 需要配置 |
| TypeScript 5.x+ | ✅ 完美支持 | ✅ 支持 |
| 社区活跃度 | 🔥 高(2026 年主流) | 📊 中等 |
推荐选择:
- 新项目:优先选择
tsx - 已有项目:继续使用
ts-node - 性能敏感:必须使用
tsx
tsconfig.json 配置
基础配置
生成的 tsconfig.json 包含所有配置项的注释,以下是 2026 年推荐的精简配置:
{
"compilerOptions": {
/* 语言环境 */
"target": "ES2022", // 编译目标(ES2022 及以上支持 TypeScript 5.x 特性)
"lib": ["ES2022"], // 包含的库文件
"jsx": "preserve", // JSX 处理方式(React 项目用 "react")
/* 模块解析 */
"module": "ESNext", // 模块系统(Node.js 项目用 "NodeNext")
"moduleResolution": "bundler", // 模块解析策略(2026 年推荐)
"resolveJsonModule": true, // 允许导入 JSON 文件
"allowImportingTsExtensions": true, // 允许导入 .ts 文件
/* 类型检查 */
"strict": true, // 启用所有严格类型检查选项
"noUnusedLocals": true, // 检查未使用的局部变量
"noUnusedParameters": true, // 检查未使用的参数
"noFallthroughCasesInSwitch": true, // switch 语句中的 fallthrough 检查
"noImplicitReturns": true, // 函数所有分支都必须返回值
/* 输出配置 */
"outDir": "./dist", // 输出目录
"rootDir": "./src", // 根目录
"declaration": true, // 生成 .d.ts 声明文件
"sourceMap": true, // 生成 source map
"removeComments": true, // 移除注释
/* 其他 */
"esModuleInterop": true, // ES 模块兼容性
"skipLibCheck": true, // 跳过库文件的类型检查(加快编译)
"forceConsistentCasingInFileNames": true // 强制文件名大小写一致
},
"include": ["src/**/*"], // 包含的文件
"exclude": ["node_modules", "dist"] // 排除的目录
}
json
不同项目类型的配置
库项目(Library)
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"moduleResolution": "bundler",
"skipLibCheck": true
}
}
json
应用项目(Application)
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"jsx": "react-jsx", // React 17+ 使用 react-jsx
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"noEmit": true, // 不生成输出文件(由构建工具处理)
"strict": true,
"skipLibCheck": true
}
}
json
Node.js 后端项目
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext", // Node.js 项目使用 NodeNext
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"sourceMap": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}
json
Monorepo 环境配置
项目结构
my-monorepo/
├── packages/
│ ├── shared/ # 共享类型和工具
│ ├── client/ # 前端应用
│ └── server/ # 后端应用
├── pnpm-workspace.yaml
├── tsconfig.base.json # 基础配置
└── package.json
text
基础配置(tsconfig.base.json)
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"strict": true,
"moduleResolution": "bundler",
"skipLibCheck": true,
"esModuleInterop": true,
"declaration": true,
"sourceMap": true
}
}
json
子包配置(packages/client/tsconfig.json)
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true, // 启用项目引用
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"references": [
{ "path": "../shared" } // 引用 shared 包
]
}
json
子包配置(packages/server/tsconfig.json)
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"references": [
{ "path": "../shared" }
]
}
json
AI 辅助配置(2026 实战)
AI 工具推荐
当遇到配置问题时,可以使用国内 AI 工具辅助:
| 工具 | 使用场景 | 示例提示词 |
|---|---|---|
| 豆包 | 配置错误诊断 | "tsconfig.json 的 moduleResolution 应该如何配置?" |
| 通义千问 | 复杂配置方案 | "Monorepo 项目中如何配置 TypeScript?" |
| 智谱清言 | 配置项解释 | "strict 模式包含哪些配置?" |
| 腾讯元宝 | 配置生成 | "为 React + Vite 项目生成 tsconfig.json" |
实战案例
案例 1:模块解析错误
// 错误:Cannot find module 'xxx' or its corresponding type declarations
import { Something } from 'xxx';
typescript
AI 辅助解决:
- 向 AI 描述问题
- AI 会检查
moduleResolution配置 - 提供解决方案:
- Node.js 项目:使用
"moduleResolution": "NodeNext" - 构建工具项目:使用
"moduleResolution": "bundler"
- Node.js 项目:使用
案例 2:类型声明找不到
# 错误:Could not find a declaration file for module 'xxx'
bash
AI 辅助解决:
- AI 会建议安装
@types/xxx - 如果没有类型包,AI 会提供:
- 自己编写声明文件的方案
- 使用
declare module临时解决方案
常见问题与解决方案
Q1: 编译速度慢
解决方案:
{
"compilerOptions": {
"skipLibCheck": true, // 跳过库文件检查
"incremental": true, // 增量编译
"tsBuildInfoFile": ".tsbuildinfo" // 构建信息文件
}
}
json
Q2: 找不到模块
解决方案:
{
"compilerOptions": {
"baseUrl": ".", // 基础路径
"paths": { // 路径映射
"@/*": ["src/*"],
"@components/*": ["src/components/*"]
}
}
}
json
Q3: JSX 配置错误
解决方案:
- React 17+:
"jsx": "react-jsx" - 旧版 React:
"jsx": "react" - Vue 3:
"jsx": "preserve"(由 Vite 处理)
线上环境
官方 Playground
官方 Playground 是在线测试 TypeScript 代码的最佳工具:
功能:
- ✅ 实时编译和类型检查
- ✅ 查看编译后的 JavaScript 代码
- ✅ 选择 TypeScript 版本
- ✅ 配置 tsconfig 选项
- ✅ 分享代码片段
使用建议:
- 快速验证语法
- 测试类型推断
- 分享问题代码
- 学习新特性
在线编辑器
- StackBlitz:https://stackblitz.com/(支持 TypeScript)
- CodeSandbox:https://codesandbox.io/(支持 TypeScript)
- Replit:https://replit.com/(支持 TypeScript)
示例扩展(保留旧命令行流程)
以下命令来自旧版笔记,适合快速体验全局 tsc:
# 全局安装(不推荐,仅供学习)
npm install typescript -g
# 查看版本
tsc -v
# 快速体验
echo "console.log('Hello ts!')" > demo.ts
tsc demo.ts && node demo.js
# 编译当前目录所有 .ts 文件
tsc *.ts
# 全局安装 ts-node(不推荐)
npm install ts-node -g
ts-node demo.ts
bash
⚠️ 重要提示:虽然现代项目建议使用本地依赖与脚本管理,但这些命令有助于对比早期工作流并复现笔记中的练习过程。
最佳实践总结
2026 年推荐实践
- 使用包管理器本地安装:避免全局安装的版本冲突
- 选择合适的运行时工具:新项目优先
tsx - 启用严格模式:
"strict": true - 配置项目引用:Monorepo 项目使用
composite: true - 利用 AI 工具:配置问题快速诊断和解决
配置检查清单
- TypeScript 版本是否为 5.x 或更高
- 是否启用了
strict模式 -
moduleResolution是否正确配置 - 是否配置了
paths路径映射 - 是否启用了增量编译
- 是否跳过了库文件检查(
skipLibCheck)
记住:好的配置是成功的一半!
↑