React

In this document, you will learn how to build a React component library with Rslib.

Create React Project

You can use create-rslib to create a project with Rslib + React. Just execute the following command:

npm
yarn
pnpm
bun
npm create rslib@latest

Then select React when prompted to "Select template".

Use Rslib in an Existing Project

To develop a React library, you need to set the target to "web" in rslib.config.ts. This is crucial because Rslib sets the target to "node" by default, which differs from the default target of Rsbuild.

To compile React (JSX and TSX), you need to register the Rsbuild React Plugin. The plugin will automatically add the necessary configuration for React builds.

For example, register in rslib.config.ts:

rslib.config.ts
1import { defineConfig } from '@rslib/core';
2import { pluginReact } from '@rsbuild/plugin-react';
3
4export default defineConfig({
5  lib: [
6    // ...
7  ],
8  output: {
9    target: 'web',
10  },
11  plugins: [pluginReact(/** options here */)],
12});

JSX Transform

  • Type: 'automatic' | 'classic'
  • Default: 'automatic'

React introduced a new JSX transform in version 17. This new transform removes the need to import React when using JSX.

By default, Rsbuild uses the new JSX transform, which is runtime: 'automatic'. It requires at least React 16.14.0 or higher. The peer dependency for React should be declared as above 16.14.0.

To change the JSX transform, you can pass the swcReactOptions option to the React plugin. For example, to use the classic runtime:

rslib.config.ts
1import { pluginReact } from '@rsbuild/plugin-react';
2import { defineConfig } from '@rslib/core';
3
4export default defineConfig({
5  lib: [
6    // ...
7  ],
8  output: {
9    target: 'web',
10  },
11  plugins: [
12    pluginReact({
13      swcReactOptions: {
14        runtime: 'classic',
15      },
16    }),
17  ],
18});

JSX Import Source

  • Type: string
  • Default: 'react'

When runtime is 'automatic', you can specify the import path of the JSX transform through importSource.

For example, when using Emotion, you can set importSource to '@emotion/react':

rslib.config.ts
1import { pluginReact } from '@rsbuild/plugin-react';
2import { defineConfig } from '@rslib/core';
3
4export default defineConfig({
5  lib: [
6    // ...
7  ],
8  output: {
9    target: 'web',
10  },
11  plugins: [
12    pluginReact({
13      swcReactOptions: {
14        importSource: '@emotion/react',
15      },
16    }),
17  ],
18});

Further Reading