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

# Declaration files

This chapter introduces what [TypeScript Declaration Files](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html) are and how to generate declaration files in Rslib.

## What is declaration files

TypeScript Declaration Files provide type information for JavaScript code. Declaration files typically have a `.d.ts` extension. They allow the TypeScript compiler to understand the type structure of JavaScript code, enabling features like:

1. **Type Checking**: Provide type information for JavaScript code, helping developers catch potential type errors at compile time.
2. **Code Completion**: Enhance code editor features like autocomplete and code navigation.
3. **Documentation Generation**: Generate documentation for JavaScript code, providing better developer experience.
4. **IDE Support**: Improve the developer experience in IDEs like Visual Studio Code, WebStorm, and others.
5. **Library Consumption**: Make it easier for users to use and understand your library.

## What are bundle declaration files and bundleless declaration files

### Bundle declaration files

Bundle declaration files involves bundling multiple TypeScript declaration files into a single declaration file.

- **Pros:**
  - **Simplified Management**: Simplifies the management and referencing of type files.
  - **Easy Distribution**: Reduces the number of files users need to handle when using the library.

- **Cons:**
  - **Complex Generation**: Generating and maintaining a single bundle file can become complex in large projects.
  - **Debugging Challenges**: Debugging type issues may not be as intuitive as with separate files.

### Bundleless declaration files

Bundleless declaration files involves generating a separate declaration file for each module in the library, just like `tsc` does.

- **Pros:**
  - **Modular**: Each module has its own type definitions, making maintenance and debugging easier.
  - **Flexibility**: Suitable for large projects, avoiding the complexity of a single file.

- **Cons:**
  - **Multiple Files**: Users may need to handle multiple declaration files when using the library.
  - **Complex Management**: May require additional configuration to correctly reference all files.

## How to generate declaration files in Rslib

Rslib's declaration generation flow can be split into two steps:

1. Type generation, that is, generate bundleless declaration files. Rslib supports the following three methods:
   - [TypeScript Compiler API](https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API)
   - [tsgo](https://github.com/microsoft/typescript-go)
   - [isolatedDeclarations](https://www.typescriptlang.org/tsconfig/#isolatedDeclarations)
2. Type bundling, that is, generate bundled declaration files (optional). When [dts.bundle](/config/lib/dts.md#dtsbundle) is enabled, Rslib bundles the generated declaration files with [API Extractor](https://api-extractor.com/).

### Generate bundleless declaration files

Bundleless declaration files can be generated in the following three ways:

| Method                            | Configuration                                    | Type checking | Output scope                                   | Speed   |
| --------------------------------- | ------------------------------------------------ | ------------- | ---------------------------------------------- | ------- |
| TypeScript Compiler API (default) | `dts: true` or `dts: { bundle: false }`          | Yes           | Determined by `tsconfig.json`                  | Slower  |
| tsgo                              | [`dts.tsgo`](/config/lib/dts.md#dtstsgo)         | Yes           | Determined by `tsconfig.json`                  | Fast    |
| isolatedDeclarations              | [`dts.isolated`](/config/lib/dts.md#dtsisolated) | No            | Modules included in the build dependency graph | Fastest |

#### TypeScript compiler API

This is the default behavior. It is mostly the same as running `tsc`: it generates declaration files and performs type checking, but it is relatively slower.

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

#### tsgo

Using [native TypeScript](https://github.com/microsoft/typescript-go) to generate declaration files keeps type checking enabled while significantly speeding up declaration generation.

When [dts.tsgo](/config/lib/dts.md#dtstsgo) is unset, Rslib enables it automatically when TypeScript 7+ is detected.


```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
```

To ensure consistency during local development, you need to install the corresponding [VS Code Preview Extension](https://marketplace.visualstudio.com/items?itemName=TypeScriptTeam.native-preview) and add the following setting to VS Code:

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

#### isolatedDeclarations

Enabling [dts.isolated](/config/lib/dts.md#dtsisolated) uses Rspack's built-in SWC fast\_dts capability to generate declaration files. This method is the fastest, but it does not perform type checking and only emits declaration files for modules included in the build dependency graph.

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

When enabling this option, we recommend also enabling [isolatedDeclarations](https://www.typescriptlang.org/tsconfig/#isolatedDeclarations) in `tsconfig.json`:

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

### Generate bundle declaration files

1. Install `@microsoft/api-extractor` as a development dependency, which is the underlying tool used for bundling declaration files.


```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. Configure in the Rslib config file:

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

### Notes

During the generation of declaration files, Rslib will automatically enforce some configuration options in `tsconfig.json` to ensure that the [TypeScript Compiler API](https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API) or [tsgo](https://github.com/microsoft/typescript-go) generates only declaration files.

```json
{
  "compilerOptions": {
    "noEmit": false,
    "declaration": true,
    "emitDeclarationOnly": true
  }
}
```

The priority from highest to lowest of final output directory of declaration files:

- The configuration option [dts.distPath](/config/lib/dts.md#dtsdistpath)
- The configuration option `declarationDir` in `tsconfig.json`
- The configuration option [output.distPath](/config/rsbuild/output.md#outputdistpath) or [output.distPath.root](/config/rsbuild/output.md#outputdistpath)

## Related configuration

| Configuration item                                                     | Description                                                                                                            |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| [dts.bundle](/config/lib/dts.md#dtsbundle)                             | Whether to bundle the declaration files.                                                                               |
| [dts.distPath](/config/lib/dts.md#dtsdistpath)                         | The output directory of declaration files.                                                                             |
| [dts.build](/config/lib/dts.md#dtsbuild)                               | Whether to generate declaration files with building the project references.                                            |
| [dts.abortOnError](/config/lib/dts.md#dtsabortonerror)                 | Whether to abort the build process when an error occurs during declaration files generation.                           |
| [dts.autoExtension](/config/lib/dts.md#dtsautoextension)               | Whether to automatically set the declaration file extension based on the [format](/config/lib/format.md) option.       |
| [dts.alias](/config/lib/dts.md#dtsalias)                               | The path alias of the declaration files.                                                                               |
| [dts.isolated](/config/lib/dts.md#dtsisolated)                         | Whether to generate declaration files with `isolatedDeclarations`.                                                     |
| [dts.tsgo](/config/lib/dts.md#dtstsgo)                                 | Whether to generate declaration files with [tsgo](https://github.com/microsoft/typescript-go).                         |
| [banner.dts](/config/lib/banner.md#bannerdts)                          | Inject content into the top of each declaration output file.                                                           |
| [footer.dts](/config/lib/footer.md#footerdts)                          | Inject content into the bottom of each declaration file.                                                               |
| [redirect.dts.path](/config/lib/redirect.md#redirectdtspath)           | Whether to automatically redirect the import paths of TypeScript declaration output files.                             |
| [redirect.dts.extension](/config/lib/redirect.md#redirectdtsextension) | Whether to automatically redirect the file extension to import paths based on the TypeScript declaration output files. |
