# TypeScript 配置 ## 库基础配置 ```json { "compilerOptions": { "target": "ESNext", "module": "ESNext", "moduleResolution": "Bundler", "lib": ["ESNext"], "strict": true, "strictNullChecks": true, "noImplicitOverride": true, "noUnusedLocals": true, "esModuleInterop": true, "skipLibCheck": true, "noEmit": true, "isolatedDeclarations": true, "verbatimModuleSyntax": true }, "include": ["src"], "exclude": ["node_modules", "dist"] } ``` ## 关键选项说明 | 选项 | 值 | 说明 | | ------------------------ | -------- | --------------------------------------------------- | | `target` | ESNext | 现代输出,由打包工具向下兼容 | | `module` | ESNext | ESM 输出 | | `moduleResolution` | Bundler | 兼容现代打包工具,允许省略扩展名 | | `strict` | true | 尽早捕获错误 | | `noEmit` | true | 由构建工具处理输出 | | `isolatedDeclarations` | true | 更快的 DTS 生成 | | `verbatimModuleSyntax` | true | 要求显式使用 `import type` | | `skipLibCheck` | true | 加快构建速度 | ## 单体仓库配置 ### 根目录 tsconfig.json ```json { "compilerOptions": { "composite": true, "declaration": true, "target": "ESNext", "module": "ESNext", "moduleResolution": "Bundler", "strict": true, "verbatimModuleSyntax": true } } ``` ### 子包 tsconfig.json ```json { "extends": "../../tsconfig.json", "compilerOptions": { "outDir": "dist", "rootDir": "src" }, "include": ["src"], "references": [ { "path": "../utils" } ] } ``` ## 路径别名 用于单体仓库的内部导入: ```json { "compilerOptions": { "paths": { "@my-lib/core": ["./packages/core/src"], "@my-lib/utils": ["./packages/utils/src"], "#internal/*": ["./virtual-shared/*"] } } } ``` ## Bundler 与 Node 解析模式对比 **对由打包工具(Vite、webpack 等)消费的库,使用 `Bundler`**: - 允许导入时不加扩展名 - 支持 package.json 中的 `exports` 字段 - 现代、更简单的配置 **对仅用于 Node.js 的库,使用 `Node16/NodeNext`**: - 需要显式扩展名(`.js`) - 更严格,与 Node.js 行为完全一致 ## 类型声明 让构建工具生成声明文件: ```typescript // tsdown.config.ts export default defineConfig({ dts: true, // 生成 .d.ts dts: { resolve: ['@antfu/utils'] } // 内联特定类型 }) ``` 或使用 unbuild: ```typescript // build.config.ts export default defineBuildConfig({ declaration: 'node16', // 为 Node.js 兼容性 declaration: true, // 为打包工具解析模式 }) ``` ## 常见问题 ### 模块未找到错误 检查 `moduleResolution` 是否与目标环境匹配: - 打包工具:`"Bundler"` - Node.js:`"Node16"` 或 `"NodeNext"` ### 类型导入不生效 启用 `verbatimModuleSyntax` 并使用显式写法: ```typescript import type { Foo } from './types' ``` ### 类型检查缓慢 启用 `skipLibCheck: true` 和 `isolatedDeclarations: true`。