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

# React

在本文档中，你将学习如何使用 Rslib 构建 React 组件库，你可在 [示例](https://github.com/rstackjs/rstack-examples/tree/main/rslib) 中查看 React 相关演示项目。

## 创建 React 项目

你可以使用 `create-rslib` 创建 Rslib + React 项目。只需执行以下命令：


```sh [npm]
npm create rslib@latest
```

```sh [yarn]
yarn create rslib
```

```sh [pnpm]
pnpm create rslib@latest
```

```sh [bun]
bun create rslib@latest
```

然后，当提示 "Select template" 时选择 `React`。

## 在现有 Rslib 项目中使用

开发 React 组件，需要在 `rslib.config.ts` 中设置 [target](/zh/config/rsbuild/output.md#outputtarget) 为 `"web"`。 这一点至关重要，因为 Rslib 默认将 `target` 设置为 `"node"`，这与 Rsbuild 的 target 默认值不同。

要编译 React（JSX 和 TSX），你需要注册 Rsbuild [React 插件](https://rsbuild.rs/zh/plugins/list/plugin-react)。该插件将自动添加 React 构建所需的配置。

例如，在 `rslib.config.ts` 中注册:

```ts title="rslib.config.ts" twoslash
import { defineConfig } from '@rslib/core';
import { pluginReact } from '@rsbuild/plugin-react'; // [!code highlight]

export default defineConfig({
  lib: [
    // ...
  ],
  // [!code highlight:4]
  output: {
    target: 'web',
  },
  plugins: [pluginReact(/** options here */)],
});
```

## JSX transform

- **类型：** `'automatic' | 'classic' | 'preserve'`
- **默认值：** `'automatic'`

React 引入了一个 [新的 JSX transform](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) 在版本 17 中。这个新的 transform 在使用 JSX 时无需导入 `React`。

默认情况下，Rslib 使用新的 JSX 转换，即 `runtime: 'automatic'`。这需要 React `16.14.0` 或更高版本，且 `peerDependencies` 中应声明 `"react": ">=16.14.0"`。

要更改 JSX transform，可以在 `@rsbuild/plugin-react` 中设置 [swcReactOptions](https://rsbuild.rs/zh/plugins/list/plugin-react#swcreactoptionsruntime) 选项。

比如要使用 classic runtime 时：

```ts title="rslib.config.ts" twoslash
import { pluginReact } from '@rsbuild/plugin-react';
import { defineConfig } from '@rslib/core';

export default defineConfig({
  lib: [
    // ...
  ],
  output: {
    target: 'web',
  },
  plugins: [
    pluginReact({
      // [!code highlight:3]
      swcReactOptions: {
        runtime: 'classic',
      },
    }),
  ],
});
```

当你希望在构建产物中保留原始 JSX 时，可以将 runtime 设置为 `'preserve'`。该模式可以保持 JSX 语法原样，不做任何转换，方便后续由其他打包工具处理。

::: warning

使用 `runtime: 'preserve'` 时，必须设置 `bundle: false` 启用 [bundleless 模式](/zh/guide/basic/output-structure.md#bundle--bundleless) 使文件保持非打包状态。

:::

若要输出 `.jsx` 后缀的文件，可通过 [output.filename](/zh/config/rsbuild/output.md#outputfilename) 配置 JS 文件名模版：

```ts title="rslib.config.ts" twoslash
import { pluginReact } from '@rsbuild/plugin-react';
import { defineConfig } from '@rslib/core';

export default defineConfig({
  lib: [
    {
      bundle: false,
      format: 'esm',
      // [!code highlight:5]
      output: {
        filename: {
          js: '[name].jsx',
        },
      },
    },
  ],
  plugins: [
    pluginReact({
      swcReactOptions: {
        runtime: 'preserve',
      },
    }),
  ],
});
```

## JSX import source

- **类型**: `string`
- **默认值**: `'react'`

当 `runtime` 的值为 `'automatic'`，可以通过 `importSource` 指定 JSX transform 的 import 路径。

例如，当使用 [Emotion](https://emotion.sh/)，你可以设置 `importSource` 为 `'@emotion/react'`:

```ts title="rslib.config.ts" twoslash
import { pluginReact } from '@rsbuild/plugin-react';
import { defineConfig } from '@rslib/core';

export default defineConfig({
  lib: [
    // ...
  ],
  output: {
    target: 'web',
  },
  plugins: [
    pluginReact({
      // [!code highlight:3]
      swcReactOptions: {
        importSource: '@emotion/react',
      },
    }),
  ],
});
```

## React Compiler

React Compiler 是一个构建时工具，它可以自动优化你的 React 应用。它支持纯 JavaScript，并且了解 React 的规则，因此你无需重写任何代码即可使用它。

在开始使用 React Compiler 之前，建议阅读 [React Compiler 文档](https://zh-hans.react.dev/learn/react-compiler)，以了解 React Compiler 的功能、当前状态和使用方法。

### 如何使用

在 Rslib 中使用 React Compiler 的步骤如下：

1. 升级 `react` 和 `react-dom` 版本到 19。如果你暂时无法升级，可以在 React 17 或 18 项目中安装 [react-compiler-runtime](https://npmjs.com/package/react-compiler-runtime)，以允许编译后的代码在 19 之前的版本上运行。
2. 通过 `@rsbuild/plugin-react` 的 `reactCompiler` 选项启用 React Compiler：

```ts title="rslib.config.ts"
import { pluginReact } from '@rsbuild/plugin-react';
import { defineConfig } from '@rslib/core';

export default defineConfig({
  plugins: [
    pluginReact({
      reactCompiler: true,
    }),
  ],
});
```

该方式使用了集成在 `builtin:swc-loader` 中的 Rust 版本 React Compiler，比 Babel 版本快约 **7-13 倍**。

> 你也可以参考 [示例项目](https://github.com/rstackjs/rstack-examples/tree/main/rslib/react-compiler)。

### 配置

传入配置对象以自定义 React Compiler 的行为。所有可用选项请参考 `@rsbuild/plugin-react` 的 [`reactCompiler`](https://rsbuild.rs/zh/plugins/list/plugin-react#reactcompiler) 选项。

```ts title="rslib.config.ts"
import { pluginReact } from '@rsbuild/plugin-react';
import { defineConfig } from '@rslib/core';

export default defineConfig({
  plugins: [
    pluginReact({
      reactCompiler: {
        compilationMode: 'annotation',
      },
    }),
  ],
});
```

对于 React 17 和 18 的项目，除了安装 [react-compiler-runtime](https://npmjs.com/package/react-compiler-runtime)，还需要指定 `target`：

```ts title="rslib.config.ts"
import { pluginReact } from '@rsbuild/plugin-react';
import { defineConfig } from '@rslib/core';

export default defineConfig({
  plugins: [
    pluginReact({
      reactCompiler: {
        target: '18', // '17' | '18' | '19'
      },
    }),
  ],
});
```

`reactCompiler` 的配置选项与 React Compiler 官方配置对齐。更多选项请参考 [React Compiler 配置文档](https://zh-hans.react.dev/reference/react-compiler/configuration)。

### 使用 Babel

你也可以使用 React Compiler 提供的 Babel 插件。这在你需要 Babel 特有的集成或 SWC transform 中尚不可用的选项时很有用。

安装 [@rsbuild/plugin-babel](https://rsbuild.rs/zh/plugins/list/plugin-babel) 和 [babel-plugin-react-compiler](https://npmjs.com/package/babel-plugin-react-compiler)，然后在 Rslib 配置文件中注册 Babel 插件：

```ts title="rslib.config.ts"
import { pluginBabel } from '@rsbuild/plugin-babel';
import { pluginReact } from '@rsbuild/plugin-react';
import { defineConfig } from '@rslib/core';

export default defineConfig({
  plugins: [
    pluginReact(),
    pluginBabel({
      include: /\.[jt]sx?$/,
      exclude: [/[\\/]node_modules[\\/]/],
      babelLoaderOptions(opts) {
        opts.plugins ??= [];
        opts.plugins.unshift('babel-plugin-react-compiler');
      },
    }),
  ],
});
```

## SVGR

阅读 [SVGR](/zh/guide/advanced/svgr-files.md) 了解更多详细信息。

## 进一步了解

- [Rsbuild React Plugin](https://rsbuild.rs/zh/plugins/list/plugin-react#swcreactoptionsruntime)
- [SWC Compilation - jsc.transform.react](https://swc.rs/docs/configuration/compilation#jsctransformreact)
