Files
2026-07-13 21:37:05 +08:00

3.4 KiB
Raw Permalink Blame History

TypeScript 配置

库基础配置

{
  "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

{
  "compilerOptions": {
    "composite": true,
    "declaration": true,
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "verbatimModuleSyntax": true
  }
}

包 tsconfig.json

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "dist",
    "rootDir": "src"
  },
  "include": ["src"],
  "references": [
    { "path": "../utils" }
  ]
}

路径别名

用于单体仓库的内部导入:

{
  "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 行为完全一致

类型声明

让构建工具生成声明:

// tsdown.config.ts
export default defineConfig({
  dts: true,                    // 生成 .d.ts
  dts: { resolve: ['@antfu/utils'] }  // 内联特定类型
})

或配合 unbuild

// build.config.ts
export default defineBuildConfig({
  declaration: 'node16',        // 为 Node.js 兼容性
  declaration: true,            // 为打包工具解析
})

常见问题

模块未找到错误

检查 moduleResolution 是否与目标环境匹配:

  • 打包工具:"Bundler"
  • Node.js"Node16""NodeNext"

类型导入不起作用

启用 verbatimModuleSyntax 并使用显式导入:

import type { Foo } from './types'

类型检查缓慢

启用 skipLibCheck: trueisolatedDeclarations: true