02 - 安装与配置
安装与配置
环境准备
前置条件
在安装 TypeScript 之前,需要确保已安装 Node.js(推荐 v18+):
# 检查 Node.js 版本
node --version # 应输出 v18.x.x 或更高
# 检查 npm 版本
npm --version # 应输出 9.x.x 或更高
安装 TypeScript
全局安装
# 使用 npm 全局安装
npm install -g typescript
# 或使用 yarn
yarn global add typescript
# 或使用 pnpm
pnpm add -g typescript
# 验证安装
tsc --version
# 输出:Version 5.x.x
项目本地安装(推荐)
# 初始化项目
mkdir my-ts-project && cd my-ts-project
npm init -y
# 作为开发依赖安装
npm install -D typescript
# 通过 npx 运行
npx tsc --version
注意:推荐使用项目本地安装,这样不同项目可以使用不同版本的 TypeScript,避免版本冲突。
包管理器对比
| 包管理器 | 安装命令 | 锁文件 | 推荐度 |
|---|---|---|---|
| npm | npm install -D typescript | package-lock.json | ⭐⭐⭐ |
| yarn | yarn add -D typescript | yarn.lock | ⭐⭐⭐ |
| pnpm | pnpm add -D typescript | pnpm-lock.yaml | ⭐⭐⭐⭐ |
| bun | bun add -d typescript | bun.lockb | ⭐⭐⭐ |
tsc 编译器
tsc(TypeScript Compiler)是 TypeScript 的核心工具。
基本用法
# 编译单个文件
tsc app.ts
# 编译多个文件
tsc app.ts utils.ts
# 使用配置文件编译(默认读取 tsconfig.json)
tsc
# 监听模式(文件变更时自动编译)
tsc --watch
# 或简写
tsc -w
常用命令行选项
# 指定输出目录
tsc --outDir dist
# 指定目标 ES 版本
tsc --target ES2022
# 启用严格模式
tsc --strict
# 指定模块系统
tsc --module ESNext
# 仅做类型检查,不输出文件
tsc --noEmit
# 显示所有编译选项
tsc --help
编译选项速查表
| 选项 | 说明 | 默认值 |
|---|---|---|
--target | 编译目标 ES 版本 | ES2016 |
--module | 模块系统 | CommonJS(Node16 时为 Node16) |
--outDir | 输出目录 | 与源文件同目录 |
--rootDir | 源文件根目录 | 自动推断 |
--strict | 启用所有严格检查 | false |
--noEmit | 不输出编译文件 | false |
--declaration | 生成 .d.ts 声明文件 | false |
--sourceMap | 生成 Source Map | false |
--esModuleInterop | ESM/CJS 互操作 | false |
--skipLibCheck | 跳过 .d.ts 文件检查 | false |
tsconfig.json
tsconfig.json 是 TypeScript 项目的配置文件,定义了编译选项和项目结构。
生成配置文件
# 生成默认的 tsconfig.json
tsc --init
完整配置示例
{
"compilerOptions": {
/* 语言和环境 */
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
/* 模块系统 */
"module": "ESNext",
"moduleResolution": "bundler",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
/* 输出 */
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
/* 严格检查 */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
/* 互操作 */
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
/* 性能 */
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
关键配置项详解
target(编译目标)
指定 TypeScript 编译输出的 ECMAScript 版本:
// target: "ES5" 时
// 解构赋值会被编译为兼容代码
const { name, age } = user;
// ↓ 编译后
// var name = user.name;
// var age = user.age;
// target: "ES2022" 时
// 解构赋值保持原样
const { name, age } = user;
| target 值 | 特性支持 | 适用场景 |
|---|---|---|
ES5 | 兼容 IE11 | 遗留项目 |
ES2015/ES6 | let/const, 箭头函数, Promise | 广泛兼容 |
ES2020 | Optional chaining, BigInt | 现代浏览器 |
ES2022 | Top-level await, Array.at() | 最新环境 |
ESNext | 所有最新特性 | 前沿项目 |
strict(严格模式)
strict: true 会开启以下所有严格检查:
| 选项 | 说明 |
|---|---|
strictNullChecks | null 和 undefined 是独立类型 |
strictFunctionTypes | 函数参数类型严格检查 |
strictBindCallApply | bind/call/apply 参数检查 |
strictPropertyInitialization | 类属性必须初始化 |
noImplicitAny | 禁止隐式 any 类型 |
noImplicitThis | 禁止隐式 this 类型 |
alwaysStrict | 输出文件包含 "use strict" |
// strictNullChecks: false(默认)
const element = document.getElementById("app"); // HTMLElement | null
element.innerHTML = "Hello"; // ✅ 不报错,但运行时可能为 null
// strictNullChecks: true
const element = document.getElementById("app"); // HTMLElement | null
element.innerHTML = "Hello"; // ❌ 编译错误:element 可能为 null
if (element) {
element.innerHTML = "Hello"; // ✅ 类型收窄后安全
}
moduleResolution(模块解析策略)
| 策略 | 说明 | 适用场景 |
|---|---|---|
node | Node.js 传统解析(CJS) | CommonJS 项目 |
node16 | Node.js 16+ 解析(CJS + ESM) | Node.js 16+ 项目 |
bundler | 打包器解析策略 | Vite/esbuild/Webpack 项目 |
nodenext | Node.js 最新解析 | Node.js 最新项目 |
项目引用
对于大型项目,可以使用项目引用(Project References)将代码拆分为多个子项目:
// tsconfig.json(根配置)
{
"files": [],
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/utils" },
{ "path": "./packages/app" }
]
}
// packages/core/tsconfig.json
{
"compilerOptions": {
"composite": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"]
}
# 构建所有项目
tsc --build
# 增量构建
tsc --build --incremental
IDE 支持
VS Code(推荐)
VS Code 内置了 TypeScript 支持,无需额外安装插件。
核心功能:
- 智能代码补全
- 实时类型检查(红色波浪线提示)
- 重构工具(重命名、提取函数等)
- 跳转到定义
- 查找所有引用
推荐插件:
| 插件 | 功能 |
|---|---|
| ESLint | 代码规范检查 |
| Prettier | 代码格式化 |
| Error Lens | 行内显示错误信息 |
| TypeScript Hero | 自动管理 import |
VS Code 设置推荐:
// .vscode/settings.json
{
"typescript.tsdk": "node_modules/typescript/lib",
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
}
}
WebStorm / IntelliJ IDEA
JetBrains 系 IDE 内置 TypeScript 支持:
- 打开
Settings → Languages & Frameworks → TypeScript - 设置 TypeScript 版本为项目本地版本
- 启用
Recompile on changes
其他编辑器
| 编辑器 | TypeScript 支持 |
|---|---|
| Sublime Text | 通过 LSP 插件支持 |
| Vim / Neovim | 通过 coc.nvim 或内置 LSP 支持 |
| Emacs | 通过 tide 或 eglot 支持 |
项目结构最佳实践
my-ts-project/
├── src/ # 源代码目录
│ ├── index.ts # 入口文件
│ ├── utils/ # 工具函数
│ │ └── helpers.ts
│ └── types/ # 类型定义
│ └── index.ts
├── dist/ # 编译输出目录
├── tests/ # 测试文件
├── tsconfig.json # TypeScript 配置
├── package.json # 项目配置
├── .eslintrc.json # ESLint 配置
└── .gitignore # Git 忽略规则
.gitignore 推荐配置:
node_modules/
dist/
*.js
*.js.map
*.d.ts
!tsconfig.json
常见问题
Q: tsc 和 ts-node 有什么区别?
| 工具 | 用途 | 输出 |
|---|---|---|
tsc | 编译 TypeScript 为 JavaScript | 生成 .js 文件 |
ts-node | 直接运行 TypeScript 文件 | 不生成文件(内存编译) |
Q: 如何在已有 JavaScript 项目中添加 TypeScript?
# 1. 安装 TypeScript
npm install -D typescript
# 2. 生成 tsconfig.json
npx tsc --init
# 3. 将 .js 文件逐步重命名为 .ts
mv src/app.js src/app.ts
Q: allowJs 和 checkJs 有什么区别?
{
"compilerOptions": {
"allowJs": true, // 允许编译 JavaScript 文件
"checkJs": true // 对 JavaScript 文件也进行类型检查
}
}
业务场景:企业级项目配置
以下是一个适合企业级 React + TypeScript 项目的配置模板:
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"baseUrl": ".",
"paths": {
"@components/*": ["src/components/*"],
"@utils/*": ["src/utils/*"],
"@hooks/*": ["src/hooks/*"],
"@types/*": ["src/types/*"]
}
},
"include": ["src/**/*", "vite-env.d.ts"],
"exclude": ["node_modules", "dist"]
}