close
  • 简体中文
  • React

    在本文档中,你将学习如何使用 Rslib 构建 React 组件库,你可在 示例 中查看 React 相关演示项目。

    创建 React 项目

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

    npm
    yarn
    pnpm
    bun
    npm create rslib@latest

    然后,当提示 "Select template" 时选择 React

    在现有 Rslib 项目中使用

    开发 React 组件,需要在 rslib.config.ts 中设置 target"web"。 这一点至关重要,因为 Rslib 默认将 target 设置为 "node",这与 Rsbuild 的 target 默认值不同。

    要编译 React(JSX 和 TSX),你需要注册 Rsbuild React 插件。该插件将自动添加 React 构建所需的配置。

    例如,在 rslib.config.ts 中注册:

    rslib.config.ts
    import { 
    function defineConfig(config: RslibConfig): RslibConfig (+3 overloads)

    This function helps you to autocomplete configuration types. It accepts a Rslib config object, or a function that returns a config.

    defineConfig
    } from '@rslib/core';
    import {
    const pluginReact: (options?: PluginReactOptions) => RsbuildPlugin
    pluginReact
    } from '@rsbuild/plugin-react';
    export default
    function defineConfig(config: RslibConfig): RslibConfig (+3 overloads)

    This function helps you to autocomplete configuration types. It accepts a Rslib config object, or a function that returns a config.

    defineConfig
    ({
    RslibConfig.lib: LibConfig[]
    lib
    : [
    // ... ],
    RslibConfig.output?: RslibOutputConfig | undefined

    Options for build outputs.

    @inheritdoc
    output
    : {
    RslibOutputConfig.target?: RsbuildTarget | undefined

    Setting the build target for Rsbuild.

    @override@default'node'
    target
    : 'web',
    },
    EnvironmentConfig.plugins?: RsbuildPlugins | undefined

    Configure Rsbuild plugins.

    plugins
    : [
    function pluginReact(options?: PluginReactOptions): RsbuildPlugin
    pluginReact
    (/** options here */)],
    });

    JSX transform

    • 类型: 'automatic' | 'classic' | 'preserve'
    • 默认值: 'automatic'

    React 引入了一个 新的 JSX transform 在版本 17 中。这个新的 transform 在使用 JSX 时无需导入 React

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

    要更改 JSX transform,可以在 @rsbuild/plugin-react 中设置 swcReactOptions 选项。

    比如要使用 classic runtime 时:

    rslib.config.ts
    import { 
    const pluginReact: (options?: PluginReactOptions) => RsbuildPlugin
    pluginReact
    } from '@rsbuild/plugin-react';
    import {
    function defineConfig(config: RslibConfig): RslibConfig (+3 overloads)

    This function helps you to autocomplete configuration types. It accepts a Rslib config object, or a function that returns a config.

    defineConfig
    } from '@rslib/core';
    export default
    function defineConfig(config: RslibConfig): RslibConfig (+3 overloads)

    This function helps you to autocomplete configuration types. It accepts a Rslib config object, or a function that returns a config.

    defineConfig
    ({
    RslibConfig.lib: LibConfig[]
    lib
    : [
    // ... ],
    RslibConfig.output?: RslibOutputConfig | undefined

    Options for build outputs.

    @inheritdoc
    output
    : {
    RslibOutputConfig.target?: RsbuildTarget | undefined

    Setting the build target for Rsbuild.

    @override@default'node'
    target
    : 'web',
    },
    EnvironmentConfig.plugins?: RsbuildPlugins | undefined

    Configure Rsbuild plugins.

    plugins
    : [
    function pluginReact(options?: PluginReactOptions): RsbuildPlugin
    pluginReact
    ({
    swcReactOptions?: ReactConfig | undefined

    Configure the behavior of SWC to transform React code, the same as SWC's jsc.transform.react.

    swcReactOptions
    : {
    ReactConfig.runtime?: "automatic" | "classic" | "preserve" | undefined

    Decides which runtime to use when transforming JSX.

    • "automatic" - Automatically imports the functions that JSX transpiles to. This is the modern approach introduced in React 17+ that eliminates the need to manually import React in every file that uses JSX.
    • "classic" - Uses the traditional JSX transform that relies on React.createElement calls. Requires React to be in scope, which was the standard behavior before React 17.
    • "preserve" - Leaves JSX syntax unchanged without transforming it.
    @default"classic"
    runtime
    : 'classic',
    }, }), ], });

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

    Warning

    使用 runtime: 'preserve' 时,必须设置 bundle: false 启用 bundleless 模式 使文件保持非打包状态。

    若要输出 .jsx 后缀的文件,可通过 output.filename 配置 JS 文件名模版:

    rslib.config.ts
    import { 
    const pluginReact: (options?: PluginReactOptions) => RsbuildPlugin
    pluginReact
    } from '@rsbuild/plugin-react';
    import {
    function defineConfig(config: RslibConfig): RslibConfig (+3 overloads)

    This function helps you to autocomplete configuration types. It accepts a Rslib config object, or a function that returns a config.

    defineConfig
    } from '@rslib/core';
    export default
    function defineConfig(config: RslibConfig): RslibConfig (+3 overloads)

    This function helps you to autocomplete configuration types. It accepts a Rslib config object, or a function that returns a config.

    defineConfig
    ({
    RslibConfig.lib: LibConfig[]
    lib
    : [
    {
    LibConfig.bundle?: boolean | undefined

    Whether to bundle the library.

    @defaultValuetrue@seehttps://rslib.rs/config/lib/bundle
    bundle
    : false,
    LibConfig.format?: Format | undefined

    Output format for the generated JavaScript files.

    @defaultValue'esm'@seehttps://rslib.rs/config/lib/format
    format
    : 'esm',
    LibConfig.output?: RslibOutputConfig | undefined

    Options for build outputs.

    @inheritdoc
    output
    : {
    OutputConfig.filename?: FilenameConfig | undefined

    Sets the filename of output files.

    filename
    : {
    js?: Filename | undefined

    The name of the JavaScript files.

    @default

    - dev: '[name].js'

    • prod: '[name].[contenthash:10].js'
    js
    : '[name].jsx',
    }, }, }, ],
    EnvironmentConfig.plugins?: RsbuildPlugins | undefined

    Configure Rsbuild plugins.

    plugins
    : [
    function pluginReact(options?: PluginReactOptions): RsbuildPlugin
    pluginReact
    ({
    swcReactOptions?: ReactConfig | undefined

    Configure the behavior of SWC to transform React code, the same as SWC's jsc.transform.react.

    swcReactOptions
    : {
    ReactConfig.runtime?: "automatic" | "classic" | "preserve" | undefined

    Decides which runtime to use when transforming JSX.

    • "automatic" - Automatically imports the functions that JSX transpiles to. This is the modern approach introduced in React 17+ that eliminates the need to manually import React in every file that uses JSX.
    • "classic" - Uses the traditional JSX transform that relies on React.createElement calls. Requires React to be in scope, which was the standard behavior before React 17.
    • "preserve" - Leaves JSX syntax unchanged without transforming it.
    @default"classic"
    runtime
    : 'preserve',
    }, }), ], });

    JSX import source

    • 类型: string
    • 默认值: 'react'

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

    例如,当使用 Emotion,你可以设置 importSource'@emotion/react':

    rslib.config.ts
    import { 
    const pluginReact: (options?: PluginReactOptions) => RsbuildPlugin
    pluginReact
    } from '@rsbuild/plugin-react';
    import {
    function defineConfig(config: RslibConfig): RslibConfig (+3 overloads)

    This function helps you to autocomplete configuration types. It accepts a Rslib config object, or a function that returns a config.

    defineConfig
    } from '@rslib/core';
    export default
    function defineConfig(config: RslibConfig): RslibConfig (+3 overloads)

    This function helps you to autocomplete configuration types. It accepts a Rslib config object, or a function that returns a config.

    defineConfig
    ({
    RslibConfig.lib: LibConfig[]
    lib
    : [
    // ... ],
    RslibConfig.output?: RslibOutputConfig | undefined

    Options for build outputs.

    @inheritdoc
    output
    : {
    RslibOutputConfig.target?: RsbuildTarget | undefined

    Setting the build target for Rsbuild.

    @override@default'node'
    target
    : 'web',
    },
    EnvironmentConfig.plugins?: RsbuildPlugins | undefined

    Configure Rsbuild plugins.

    plugins
    : [
    function pluginReact(options?: PluginReactOptions): RsbuildPlugin
    pluginReact
    ({
    swcReactOptions?: ReactConfig | undefined

    Configure the behavior of SWC to transform React code, the same as SWC's jsc.transform.react.

    swcReactOptions
    : {
    ReactConfig.importSource?: string | undefined

    Declares the module specifier to be used for importing the jsx and jsxs factory functions when using runtime 'automatic'

    @default"react"
    importSource
    : '@emotion/react',
    }, }), ], });

    React Compiler

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

    在开始使用 React Compiler 之前,建议阅读 React Compiler 文档,以了解 React Compiler 的功能、当前状态和使用方法。

    如何使用

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

    1. 升级 reactreact-dom 版本到 19。如果你暂时无法升级,可以在 React 17 或 18 项目中安装 react-compiler-runtime,以允许编译后的代码在 19 之前的版本上运行。
    2. 目前 React Compiler 仅提供了 Babel 插件,你需要安装 @rsbuild/plugin-babelbabel-plugin-react-compiler
    3. 在你的 Rslib 配置文件中注册 Babel 插件:
    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');
          },
        }),
      ],
    });
    Tip

    include 使用 /\.[jt]sx?$/ 来匹配 .js.jsx.ts.tsx 文件。这样可以确保 React Compiler 能够优化组件和自定义 Hooks,因为自定义 Hooks 通常定义在 .ts 文件中。exclude 中的 node_modules 可以防止编译器处理第三方依赖。

    如果你只想编译 JSX/TSX 文件,可以使用 include: /\.(?:jsx|tsx)$/,但 .ts 文件中的自定义 Hooks 将不会被优化。

    你也可以参考 示例项目

    配置

    通过以下方式来传入 React Compiler 的配置:

    rslib.config.ts
    import { pluginBabel } from '@rsbuild/plugin-babel';
    import { pluginReact } from '@rsbuild/plugin-react';
    import { defineConfig } from '@rslib/core';
    
    const ReactCompilerConfig = {
      /* ... */
    };
    
    export default defineConfig({
      plugins: [
        pluginReact(),
        pluginBabel({
          include: /\.[jt]sx?$/,
          exclude: [/[\\/]node_modules[\\/]/],
          babelLoaderOptions(opts) {
            opts.plugins ??= [];
            opts.plugins.unshift([
              'babel-plugin-react-compiler',
              ReactCompilerConfig,
            ]);
          },
        }),
      ],
    });

    对于 React 17 和 18 的项目,除了安装 react-compiler-runtime,还需要指定 target

    rslib.config.ts
    const ReactCompilerConfig = {
      target: '18', // '17' | '18' | '19'
    };

    SVGR

    阅读 SVGR 了解更多详细信息。

    进一步了解