Redon

一心的小屋

TSConfig备忘录

发布于 # TypeScript

原文来自:The TSConfig Cheat Sheet (Matt Pocock),本人翻译备份用。

tsconfig.json 文件让很多人望而生畏,因为它是一个庞大的文件,包含着大量的配置选项。

但实际上,只需要关注其中较少的几个配置选项就行了。让我们来理清这些选项,并做成简易参考。

快速开始

基本代码示例

{
  "compilerOptions": {
    /* 基础选项: */
    "esModuleInterop": true,
    "skipLibCheck": true,
    "target": "es2022",
    "allowJs": true,
    "resolveJsonModule": true,
    "moduleDetection": "force",
    "isolatedModules": true,
    "verbatimModuleSyntax": true,
    /* 严格模式 */
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    /* 如果使用 TypeScript 转码: */
    "module": "NodeNext",
    "outDir": "dist",
    "sourceMap": true,
    /* 如果要构建一个库: */
    "declaration": true,
    /* 如果要在单一仓库中构建一个库: */
    "composite": true,
    "declarationMap": true,
    /* 如果不使用 TypeScript 进行转码: */
    "module": "preserve",
    "noEmit": true,
    /* 如果代码运行在 DOM 中: */
    "lib": ["es2022", "dom", "dom.iterable"],
    /* 如果代码不运行在 DOM 中: */
    "lib": ["es2022"]
  }
}

完整说明

基本选项

以下是我推荐所有项目都使用的基础选项:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "skipLibCheck": true,
    "target": "es2022",
    "allowJs": true,
    "resolveJsonModule": true,
    "moduleDetection": "force",
    "isolatedModules": true,
    "verbatimModuleSyntax": true
  }
}

严格模式

以下是我推荐所有项目使用的严格模式选项:

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true
  }
}

许多人推荐 tsconfig/bases 中的严格模式选项,这是一个很棒的存储库,它列举了 TSConfig 选项。 但这些选项包含了许多我认为过于“繁琐”的规则,例如 noImplicitReturnsnoUnusedLocalsnoUnusedParametersnoFallthroughCasesInSwitch。 我建议仅在你想要它们时才将这些规则添加到你的 tsconfig.json 中。

使用 TypeScript 进行转码

如果你正在使用 tsc 转码你的代码(创建 JavaScript 文件),则需要以下选项:

{
  "compilerOptions": {
    "module": "NodeNext",
    "outDir": "dist"
  }
}

构建库

如果你要构建一个库,则需要 declaration: true

{
  "compilerOptions": {
    "declaration": true
  }
}

单仓库中的库构建

如果您要为单仓库中的库构建,那么您还需要以下选项:

{
  "compilerOptions": {
    "declaration": true,
    "composite": true,
    "sourceMap": true,
    "declarationMap": true
  }
}

不使用 TypeScript 进行转译

如果您不使用 tsc 转译您的代码,即更像使用 TypeScript 作为 linter,那么您将需要以下选项:

{
  "compilerOptions": {
    "module": "preserve",
    "noEmit": true
  }
}

DOM 中运行

如果你的代码在 DOM 中运行,则需要以下选项:

{
  "compilerOptions": {
    "lib": ["es2022", "dom", "dom.iterable"]
  }
}

不在 DOM 中运行

如果你的代码不在 DOM 中运行,则您需要 lib: ["es2022"]

{
  "compilerOptions": {
    "lib": ["es2022"]
  }
}

这与上面相同,但没有 domdom.iterable 类型。