使用 TypeScript
Rsbuild 默认支持 TypeScript,你可以直接在项目中使用 .ts 和 .tsx 文件。
TypeScript 转译
Rsbuild 默认使用 SWC 来转译 TypeScript 代码,也支持切换到 Babel 进行转译。
isolatedModules
与 TypeScript 原生编译器不同,像 SWC 和 Babel 这样的工具会将每个文件单独编译,它无法确定导入的名称是一个类型还是一个值。因此,当你在 Rsbuild 中使用 TypeScript 时,需要启用 tsconfig.json 中的 isolatedModules 选项:
tsconfig.json
{"compilerOptions": {"isolatedModules": true}}
该选项可以帮助你避免使用一些 SWC 和 Babel 无法正确编译的写法,比如跨文件的类型引用问题,它会引导你更正对应的用法:
// 错误export { SomeType } from './types';// 正确export type { SomeType } from './types';
参考 SWC - Migrating from tsc 了解更多 SWC 和 tsc 的差异。
预设类型
@rsbuild/core 提供了一些预设的类型定义,包含 CSS Modules、静态资源、import.meta 等类型。
你可以创建一个 src/env.d.ts 文件来引用:
src/env.d.ts
/// <reference types="@rsbuild/core/types" />
类型检查
在进行 TypeScript 转译时,SWC 和 Babel 等工具不会执行类型检查。
Rsbuild 提供了 Type Check 插件,用于在单独的进程中运行 TypeScript 类型检查,插件内部集成了 fork-ts-checker-webpack-plugin。
请参考 @rsbuild/plugin-type-check 了解用法。
tsconfig.json 路径
Rsbuild 默认读取根目录的 tsconfig.json 文件,你可以使用 source.tsconfigPath 配置自定义的 tsconfig.json 文件路径。
export default {source: {tsconfigPath: './tsconfig.custom.json',},};
路径后缀
当在一个 TypeScript 模块中导入另一个模块时,TypeScript 允许使用 .js 文件扩展名:
src/index.ts
// 实际引用的模块可能是 `./some-module.ts` 或 `./some-module.tsx`import { someFn } from './some-module.js';
Rsbuild 通过 Rspack 的 extensionAlias 配置来支持该特性。在 TypeScript 项目中,Rsbuild 默认会添加以下配置:
const rspackConfig = {resolve: {extensionAlias: {'.js': ['.ts', '.tsx', '.js'],'.jsx': ['.tsx', '.jsx'],},},};
这意味着:
- 允许使用
.js文件扩展名导入.ts或.tsx文件。 - 允许使用
.jsx文件扩展名导入.tsx文件。
