> For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt.

# lib.dts

- **类型：**

```ts
type Dts =
  | {
      bundle?: boolean | { tsconfigPath?: string; bundledPackages?: string[] };
      distPath?: string;
      build?: boolean;
      abortOnError?: boolean;
      autoExtension?: boolean;
      alias?: Record<string, string>;
      isolated?: boolean;
      typescriptPath?: string;
      tsgo?: boolean;
    }
  | boolean;
```

- **默认值：** `undefined`
- **命令行：** `--dts` / `--no-dts`
- **顶层配置：** 支持

配置 TypeScript 声明文件的生成。

顶层 `dts` 会被所有 `lib` 配置项继承，但配置项自身的 `dts` 具有更高优先级。

:::warning
存在多个 `lib` 配置项时，使用顶层 `dts` 可能导致类型声明生成过程中的文件写入或删除操作发生冲突，建议改为在具体的 `lib` 配置项中配置 `dts`。
:::

## 布尔类型

类型声明文件生成是一个可选功能，你可以设置 `dts: true` 来启用 [bundleless 类型](/zh/guide/advanced/dts.md#bundleless-类型) 生成。

```ts title="rslib.config.ts"
export default {
  lib: [
    {
      format: 'esm',
      dts: true, // [!code highlight]
    },
  ],
};
```

如果你想要禁用类型声明文件生成，可以设置 `dts: false` 或者不指定 `dts` 选项。

```ts title="rslib.config.ts"
export default {
  lib: [
    {
      format: 'esm',
      dts: false, // [!code highlight]
    },
  ],
};
```

## 对象类型

如果你想要自定义类型声明文件的生成，可以将 `dts` 选项设置为一个对象。

### dts.bundle

- **类型：** `boolean | { tsconfigPath?: string; bundledPackages?: string[] }`
- **默认值：** `false`

是否打包类型声明文件。

如果你想要 [bundle 类型](/zh/guide/advanced/dts.md#bundle-类型)，你需要：

1. 安装 [@microsoft/api-extractor](https://www.npmjs.com/package/@microsoft/api-extractor) 作为开发依赖，它是用于打包类型声明文件的底层工具。


```sh [npm]
npm add @microsoft/api-extractor -D
```

```sh [yarn]
yarn add @microsoft/api-extractor -D
```

```sh [pnpm]
pnpm add @microsoft/api-extractor -D
```

```sh [bun]
bun add @microsoft/api-extractor -D
```

```sh [deno]
deno add npm:@microsoft/api-extractor -D
```

2. 将 `dts.bundle` 设置为 `true`。

```ts title="rslib.config.ts"
export default {
  lib: [
    {
      format: 'esm',
      // [!code highlight:3]
      dts: {
        bundle: true,
      },
    },
  ],
};
```

::: note 使用限制

Rslib 基于 API Extractor 对类型声明文件进行打包，可能会存在一些由 API Extractor 静态分析能力带来的限制，例如遇到复杂 re-export、特定解构语法、依赖生成的特殊声明文件或无法解析的导出时，可能会出现 `Internal Error: Unable to analyze the export ...` 等报错，此时建议关闭 `dts.bundle` 使用 bundleless 类型输出。

:::

#### dts.bundle.tsconfigPath

- **类型：** `string`
- **默认值：** [source.tsconfigPath](/zh/config/rsbuild/source.md#sourcetsconfigpath)

配置 API Extractor 打包类型声明文件时使用的自定义 tsconfig.json 文件路径，相对路径基于项目根目录解析。

开启类型声明文件打包后，Rslib 会在两个阶段使用 TypeScript 配置：

- [source.tsconfigPath](/zh/config/rsbuild/source.md#sourcetsconfigpath) 用于在 `.rstack/declarations` 目录中生成临时类型声明文件。
- `dts.bundle.tsconfigPath` 由 API Extractor 用于分析并打包上述生成的临时类型声明文件。

默认情况下，两个阶段都使用 `source.tsconfigPath`。如果希望 API Extractor 使用独立的 TypeScript 配置，例如单独调整 `paths` 等模块解析选项，可以按如下方式配置：

```ts title="rslib.config.ts"
export default {
  lib: [
    {
      dts: {
        bundle: {
          tsconfigPath: './tsconfig.dts-bundle.json',
        },
      },
    },
  ],
};
```

#### dts.bundle.bundledPackages

- **类型：** `string[]`

用于指定需要打包类型声明文件的依赖项，该配置将传递给 `@microsoft/api-extractor` 的 [bundledPackages](https://api-extractor.com/pages/configs/api-extractor_json/#bundledpackages) 配置项。

默认情况下，Rslib 会根据以下配置确定需要外部化的依赖项，详见 [处理第三方依赖](/zh/guide/advanced/third-party-deps.md)。

- [output.autoExternal](/zh/config/rsbuild/output.md#outputautoexternal) 配置
- [output.externals](/zh/config/rsbuild/output.md#outputexternals) 配置

那些没有被外部化的直接依赖项（在 `package.json` 中声明）会被添加到 `bundledPackages` 中，这些包的类型声明文件将会被打包到最终的产物中。

当默认行为不能满足需求时，可以通过 `dts.bundle.bundledPackages` 显式指定需要打包的依赖项。设置该配置后，将完全覆盖上述默认行为。

该配置通常用于打包传递依赖项（即直接依赖的依赖）。假设项目直接依赖 `foo`，而 `foo` 又依赖 `bar`，如果需要同时打包 `foo` 和 `bar` 的类型声明文件，可以如下配置：

```ts title="rslib.config.ts"
export default {
  lib: [
    {
      format: 'esm',
      dts: {
        // [!code highlight:3]
        bundle: {
          bundledPackages: ['foo', 'bar'],
        },
      },
    },
  ],
};
```

::: note
`bundledPackages` 可以使用 [minimatch](https://www.npmjs.com/package/minimatch) 语法配置 glob 表达式，但仅会匹配 `package.json` 中已声明的直接依赖项。
:::

### dts.distPath

- **类型：** `string`

类型声明文件的输出目录。

#### 默认值

默认值按照以下优先级确定：

1. 当前 lib 配置中的 `dts.distPath` 值。
2. `tsconfig.json` 文件中的 `declarationDir` 值。
3. 当前 lib 配置中的 [output.distPath](/zh/config/rsbuild/output.md#outputdistpath) 值或 [output.distPath.root](/zh/config/rsbuild/output.md#outputdistpath) 值。

#### 示例

```ts title="rslib.config.ts"
export default {
  lib: [
    {
      format: 'esm',
      // [!code highlight:3]
      dts: {
        distPath: './dist-types',
      },
    },
  ],
};
```

### dts.build

- **类型：** `boolean`
- **默认值：** `false`

是否在生成类型声明文件时构建项目的 project references。这相当于在 `tsc` 命令中使用 `--build` 标志。更多详细信息请参考 [项目引用](https://www.typescriptlang.org/docs/handbook/project-references.html)。

在配置了 project references 但被引用的项目尚未单独构建时（例如在 monorepo 中直接引用其他项目的源代码，但项目中缺少对应的类型声明文件），需要开启此选项，以确保能够正确生成依赖项目的类型声明，从而保障类型系统的完整性。

::: note

- 该选项仅可在 [dts.bundle](/zh/config/lib/dts.md#dtsbundle) 为 `false` 时使用。
- 当启用该选项时，需要在 `tsconfig.json` 中显式设置 `declarationDir` 或 `outDir` 以满足构建要求。

:::

### dts.abortOnError

- **类型：** `boolean`
- **默认值：** `true`

当类型声明文件生成过程中出现错误时，是否中止构建过程。

默认情况下，类型错误会导致构建失败。

当 `abortOnError` 设置为 `false` 时（如下所示），即使代码中存在类型问题，构建仍然会成功。

```ts title="rslib.config.ts"
export default {
  lib: [
    {
      format: 'esm',
      // [!code highlight:3]
      dts: {
        abortOnError: false,
      },
    },
  ],
};
```

::: warning

当禁用该配置时，无法保证类型文件会被正确生成。

:::

### dts.autoExtension

- **类型：** `boolean`
- **默认值：** `false`

是否根据 [format](/zh/config/lib/format.md) 选项自动设置类型声明文件扩展名。

#### 默认扩展名

当 `dts.autoExtension` 为 `false` 时，类型声明文件扩展名默认为 `.d.ts`。

当 `dts.autoExtension` 设置为 `true` 时，类型声明文件扩展名将会是：

- 当 `package.json` 中设置 `type: module` 时，`esm` 格式使用 `.d.ts`，`cjs` 格式使用 `.d.cts`。

- 当 `package.json` 中设置 `type: commonjs` 或没有 `type` 字段时，`cjs` 格式使用 `.d.ts`，`esm` 格式使用 `.d.mts`。

::: note

1. 这遵循与 [lib.autoExtension](/zh/config/lib/auto-extension.md) 相同的逻辑，但默认值不同，因为类型声明文件扩展名可能会在不同的模块解析策略中造成一些问题。

2. 类型声明文件的导入路径扩展名重写由 [redirect.dts.extension](/zh/config/lib/redirect.md#redirectdtsextension) 控制。

3. 当开启 [dts.tsgo](/zh/config/lib/dts.md#dtstsgo) 时，如果项目同时开启了 [dts.build](/zh/config/lib/dts.md#dtsbuild) 或者将不同后缀的类型声明文件输出到同一目录，`dts.autoExtension` 无法正常生效。

:::

### dts.alias

- **类型：** `Record<string, string>`
- **默认值：** `{}`

用于配置类型声明文件的路径别名。

在 `dts.alias` 中配置的路径别名，其相对路径应基于 `tsconfig.json` 中 `compilerOptions.baseUrl` 所指定的目录。这些别名会与 `compilerOptions.paths` 进行合并，且 `dts.alias` 的优先级更高。

大部分情况下，你不需要使用 `dts.alias`，但当你需要在类型声明文件中使用路径别名却不希望影响 JavaScript 产物时，可以考虑使用它。比如，将 `foo` 的类型声明文件指向 `./compiled/foo`。

```ts title="rslib.config.ts"
export default {
  lib: [
    {
      // [!code highlight:5]
      dts: {
        alias: {
          foo: './compiled/foo',
        },
      },
    },
  ],
};
```

此时，当 [redirect.dts.path](/zh/config/lib/redirect.md#redirectdtspath) 开启时，类型声明文件中对 `foo` 的导入路径将会被重定向为 `./compiled/foo`。

```diff title="index.d.ts"
- export * from 'foo';
+ export * from './compiled/foo';
```

### dts.typescriptPath

- **类型：** `string`
- **默认值：** 从项目根目录解析到的 `typescript` 路径

指定 TypeScript 模块入口的自定义绝对路径。

如果项目使用 TypeScript 6，并希望尝试用 TypeScript 7 生成类型声明，可以通过 [npm alias](https://devblogs.microsoft.com/typescript/announcing-typescript-7-0/#running-side-by-side-with-typescript-6.0) 安装这两个版本：

```json title="package.json"
{
  "devDependencies": {
    "@typescript/native": "npm:typescript@^7.0.2",
    "typescript": "npm:@typescript/typescript6@^6.0.2"
  }
}
```

然后在 Rslib 配置中，将 `dts.typescriptPath` 指向 `@typescript/native` 提供的 TypeScript 7：

```ts title="rslib.config.ts"
import { fileURLToPath } from 'node:url';
import { defineConfig } from '@rslib/core';

export default defineConfig({
  lib: [
    {
      dts: {
        typescriptPath: fileURLToPath(
          import.meta.resolve('@typescript/native'),
        ),
      },
    },
  ],
});
```

### dts.tsgo

- **类型：** `boolean`
- **默认值：** 检测到 TypeScript 7+ 时为 `true`，否则为 `false`

是否通过 [native TypeScript](https://github.com/microsoft/typescript-go) 生成类型声明文件。

如果没有显式设置该选项，Rslib 会在检测到 TypeScript 7+ 时自动开启。配置 [dts.typescriptPath](#dtstypescriptpath) 后，Rslib 会根据解析到的 TypeScript 版本决定是否自动启用 `tsgo`。


```sh [npm]
npm add typescript@latest -D
```

```sh [yarn]
yarn add typescript@latest -D
```

```sh [pnpm]
pnpm add typescript@latest -D
```

```sh [bun]
bun add typescript@latest -D
```

```sh [deno]
deno add npm:typescript@latest -D
```

为了保证本地开发的一致性，你需要安装对应的 [VS Code 预览版扩展](https://marketplace.visualstudio.com/items?itemName=TypeScriptTeam.native-preview)，并在 VS Code 设置中添加如下配置：

```json title=".vscode/settings.json"
{
  "typescript.experimental.useTsgo": true
}
```

### dts.isolated

- **类型：** `boolean`
- **默认值：** `false`

是否使用 `isolatedDeclarations` 生成类型声明文件。

:::tip

该选项目前是实验性能力。

:::

开启后，Rslib 会通过 Rspack 内置的 SWC fast\_dts 能力，在构建过程中直接生成类型声明文件。

```ts title="rslib.config.ts"
export default {
  lib: [
    {
      dts: {
        isolated: true, // [!code highlight]
      },
    },
  ],
};
```

启用该选项时，建议同时在 `tsconfig.json` 中开启 [isolatedDeclarations](https://www.typescriptlang.org/tsconfig/#isolatedDeclarations)，让 TypeScript 提前暴露不满足 `isolatedDeclarations` 约束的代码。

```json title="tsconfig.json"
{
  "compilerOptions": {
    "isolatedDeclarations": true
  }
}
```

::: info 使用条件

- `dts.isolated` 不能与 [dts.typescriptPath](/zh/config/lib/dts.md#dtstypescriptpath) 同时开启。
- `dts.isolated` 不能与 [dts.tsgo](/zh/config/lib/dts.md#dtstsgo) 同时开启。
- `dts.isolated` 不能与 [dts.build](/zh/config/lib/dts.md#dtsbuild) 同时开启。
- 开启 `dts.isolated` 时，不能将 [dts.abortOnError](/zh/config/lib/dts.md#dtsabortonerror) 设置为 `false`。

:::

#### 适用场景

Rslib 默认通过 TypeScript Compiler API 生成类型声明文件，也可以通过 `dts.tsgo` 使用 `tsgo` 生成类型声明文件。与这两种方式不同，`dts.isolated` 速度最快，适合追求构建性能的场景。

由于 `dts.isolated` 不会在声明文件生成阶段执行类型检查，所以通常需要与其他独立的高性能类型检查流程搭配使用。例如在 monorepo 项目中，可以配合 [`rslint --type-check`](https://rslint.rs/guide/type-checking) 使用该选项：

- 日常构建：由 `dts.isolated` 负责在各个包构建时快速输出类型声明文件。
- 全局检查：在 CI 或 pre-commit hook 中运行 `rslint --type-check`，按需执行统一的类型检查。

这样既能保留完整的类型检查，又能减少每个包在构建阶段重复执行 TypeScript 类型分析、加载 TypeScript 或 `tsgo` 相关包及 native binding 的开销，让整体构建链路更轻量。

#### 输出范围

`dts.isolated` 基于 Rspack 构建时的模块依赖图生成类型声明文件。只有入口模块以及被入口模块引用到的模块会生成对应的声明文件。如果某个文件没有进入构建依赖图，它不会像 TypeScript 那样自动生成声明文件。如果你希望这类文件也生成声明文件，可以把它们加入 [source.entry](/zh/config/rsbuild/source.md#sourceentry)，或确保它们被现有入口引用。
