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

# 使用 TypeScript

Rslib 默认支持 TypeScript，你可以直接在项目中使用 `.ts` 和 `.tsx` 文件。

## TypeScript 转译

Rslib 默认使用 SWC 进行 TypeScript 代码的转译，同时也支持切换到 Babel 进行转译。

### isolatedModules

不同于原生的 TypeScript 编译器，SWC 和 Babel 这类工具会单独编译每个文件，这会导致无法确定导入的名称是类型还是值。因此，在 Rslib 中使用 TypeScript 时，你需要在 `tsconfig.json` 文件中启用 [isolatedModules](https://typescriptlang.org/tsconfig/#isolatedModules) 选项：

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

这个选项可以帮助你避免使用某些在 SWC 和 Babel 中无法正确编译的语法，例如跨文件的类型引用。它会引导你修正为对应正确的用法：

```ts
// 错误
export { SomeType } from './types';

// 正确
export type { SomeType } from './types';
```

> 更多关于 SWC 和 tsc 之间差异的详细信息，可以查看 [SWC - Migrating from tsc](https://swc.rs/docs/migrating-from-tsc)。

## 预设类型

`@rslib/core` 提供了一些预设的类型定义，包含 CSS Modules、静态资源、`import.meta` 等类型。

你可以在 `tsconfig.json` 的 [`compilerOptions.types`](https://www.typescriptlang.org/tsconfig/#types) 中添加这些预设类型：

```json title="tsconfig.json"
{
  "compilerOptions": {
    "types": ["@rslib/core/types"]
  }
}
```

如果你的项目中已经配置了 `compilerOptions.types`，请将 `@rslib/core/types` 追加到已有列表中。

> Rslib 的预设类型与 Rsbuild 的预设类型相同。参考 Rsbuild 的 [types.d.ts](https://github.com/web-infra-dev/rsbuild/blob/main/packages/core/types.d.ts) 来了解完整类型定义。

## 类型检查

在进行 TypeScript 转译时，SWC 和 Babel 等工具不会执行类型检查。

Rslib 提供了 [lib.dts](/zh/config/lib/dts.md) 配置项用于生成 TypeScript 声明文件，生成过程中默认会进行类型检查。

你可以在 `tsconfig.json` 文件中将 [noCheck](https://www.typescriptlang.org/tsconfig/#noCheck) 配置项设置为 `true` 来跳过类型检查。

## tsconfig.json 路径

Rslib 默认从根目录下读取 `tsconfig.json` 文件。你可以使用 [source.tsconfigPath](/zh/config/rsbuild/source.md#sourcetsconfigpath) 配置一个自定义的 `tsconfig.json` 文件路径。

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

## 装饰器版本

Rslib 默认使用 [`2023-11`](https://rsbuild.rs/zh/config/source/decorators#2023-11) 版本的装饰器。

如果在 `tsconfig.json` 中启用了 [experimentalDecorators](https://www.typescriptlang.org/tsconfig/#experimentalDecorators)，Rslib 会默认将 [source.decorators.version](/zh/config/rsbuild/source.md#sourcedecorators) 设置为 `legacy` 来使用旧版本装饰器。
