一、基础编译命令
1.1 基本用法
tsc [文件名] # 编译单个文件
tsc src/*.ts # 编译目录下所有TS文件
tsc --project tsconfig.prod.json # 指定配置文件
1.2 关键编译选项
选项 | 示例 | 功能说明 |
---|---|---|
--target |
--target ES2020 |
指定ECMAScript目标版本 |
--module |
--module ESNext |
指定模块系统(CommonJS/ESNext等) |
--outDir |
--outDir ./dist |
指定输出目录 |
--declaration |
--declaration |
生成类型声明文件(.d.ts) |
--watch |
--watch |
启用文件监听模式 |
二、tsconfig.json核心配置
2.1 基础配置结构
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"strict": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
2.2 严格模式配置
{
"strict": true, // 启用所有严格检查
"noImplicitAny": true, // 禁止隐式any类型
"strictNullChecks": true, // 严格空值检查
"strictFunctionTypes": true // 严格函数类型检查
}
三、模块系统配置
3.1 模块语法示例
// 命名导出
export function utils() {}
export const PI = 3.14;
// 默认导出
export default class Main {}
// 导入
import Main, { utils, PI } from './module';
import * as all from './module';
3.2 模块解析配置
{
"compilerOptions": {
"moduleResolution": "node",
"baseUrl": "./src",
"paths": {
"@components/*": ["components/*"],
"@utils/*": ["utils/*"]
}
}
}
四、高级编译特性
4.1 增量编译
{
"compilerOptions": {
"incremental": true,
"tsBuildInfoFile": "./.tsbuildinfo"
}
}
4.2 项目引用配置
// tsconfig.json(顶层配置)
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
4.3 路径映射配置
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"shared/*": ["shared/*"]
}
}
}
五、常见问题解决
5.1 模块找不到错误
# 解决方案1:检查paths配置
{
"compilerOptions": {
"paths": {
"@utils/*": ["src/utils/*"]
}
}
}
# 解决方案2:安装类型定义包
npm install --save-dev @types/node
5.2 编译性能优化
{
"compilerOptions": {
"skipLibCheck": true, // 跳过库文件检查
"isolatedModules": true // 独立模块编译
}
}
六、最佳实践配置示例
6.1 React项目配置
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"jsx": "react-jsx",
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"],
"exclude": ["node_modules"]
}
6.2 Node.js项目配置
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
七、调试与诊断
7.1 显示完整配置
tsc --showConfig # 显示实际使用的配置
tsc --listFiles # 显示编译文件列表
tsc --diagnostics # 显示编译统计信息
7.2 SourceMap配置
{
"compilerOptions": {
"sourceMap": true,
"inlineSources": true,
"sourceRoot": "/src"
}
}
通过合理配置tsc
命令和tsconfig.json
文件,可以显著提升TypeScript项目的开发效率和代码质量。建议根据项目规模和需求,逐步引入高级配置特性。