工具链
tsc、ts-node、compiler options、lint/format、build tools。
30 分钟
工具链
写出正确类型只是第一步;tsc、ts-node、compiler options、ESLint、Prettier、打包器 共同决定开发体验与产物质量。本课梳理 TypeScript 工具链,衔接 typescript-essentials,并对照 platform 与 nextjs-essentials(SWC 编译)、nestjs-essentials(tsc + nest build)的实际配置。
学习目标
- 读懂 tsconfig 核心选项:strict、moduleResolution、paths
- 区分 tsc 类型检查 vs 打包器转译
- 配置 ESLint TypeScript 规则与项目引用
tsconfig 核心选项
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUncheckedIndexedAccess": true,
"skipLibCheck": true,
"esModuleInterop": true,
"jsx": "preserve",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
| 选项 | 作用 |
|---|---|
strict | 开启全部严格检查 |
noUncheckedIndexedAccess | 索引访问返回 T | undefined |
moduleResolution: bundler | 配合 Vite/Next 解析 |
paths | 路径别名,需打包器同步配置 |
tsc 职责边界
tsc --noEmit → 仅类型检查(CI 常用)
tsc → 类型检查 + 输出 .js + .d.ts
Next.js / Vite → SWC/esbuild 转译,tsc 或 IDE 做类型
# 仅检查
npx tsc --noEmit
# 生成声明文件
npx tsc --declaration --emitDeclarationOnly
ts-node 与 tsx
# 开发脚本直接运行 TS
npx tsx scripts/seed.ts
# ts-node(需 tsconfig 配合)
npx ts-node --esm scripts/migrate.ts
ESLint + Prettier
// .eslintrc 片段
{
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended-type-checked"
],
"parserOptions": {
"project": "./tsconfig.json"
},
"rules": {
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-floating-promises": "error"
}
}
Project References
// packages/shared/tsconfig.json
{
"compilerOptions": {
"composite": true,
"declaration": true,
"outDir": "./dist"
}
}
// apps/platform/tsconfig.json
{
"references": [{ "path": "../../packages/shared" }]
}