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

# 配置

Storybook Rsbuild 提供了多种自定义构建流程和行为的方式。本指南介绍可在 `.storybook/main.ts` 中使用的配置项。

:::tip Storybook 文档
本指南聚焦于 Rsbuild 特有的配置。关于通用的 Storybook 配置（stories、addons、refs 等），请参阅 [Storybook Configure](https://storybook.js.org/docs/configure) 文档。
:::

## rsbuildFinal

`rsbuildFinal` 字段让你能够直接访问 Rsbuild 配置。你可以用它来自定义构建配置，类似于 Webpack builder 中的 [webpackFinal](https://storybook.js.org/docs/builders/webpack#extending-storybooks-webpack-config)。

该函数接收当前的 Rsbuild 配置和一个 options 对象，并应返回修改后的配置。

:::warning 使用 `mergeRsbuildConfig` 进行修改
在 `rsbuildFinal` 中应始终使用来自 `@rsbuild/core` 的 [`mergeRsbuildConfig`](https://rsbuild.rs/api/javascript-api/core#mergersbuildconfig) 修改配置；不支持返回全新的配置对象。直接替换 `config.tools.rspack = {...}` 等属性也可能被静默忽略，因为内部配置可能是由函数和对象组成的数组。使用函数形式的 `tools.rspack` 时，请修改并返回传入的配置，或使用回调提供的 `mergeConfig`；返回全新对象会静默丢弃 Storybook 注入的配置，例如 `sb.mock` 机制。
:::

```ts twoslash title=".storybook/main.ts"
// @noErrors
import type { StorybookConfig } from 'storybook-react-rsbuild'
import { mergeRsbuildConfig } from '@rsbuild/core'

const config: StorybookConfig = {
  framework: 'storybook-react-rsbuild',
  stories: ['../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  addons: [],
  async rsbuildFinal(config, { configType }) {
    // Customize Rsbuild config here
    if (configType === 'PRODUCTION') {
      return mergeRsbuildConfig(config, {
        performance: {
          removeConsole: true,
        },
      })
    }

    // Example: add resolve alias
    return mergeRsbuildConfig(config, {
      resolve: {
        alias: {
          '@components': './src/components',
        },
      },
    })
  },
}

export default config
```

## Builder 选项

你可以通过 `core.builder` 选项配置底层的 Rsbuild builder。

```ts twoslash title=".storybook/main.ts"
// @noErrors
import type { StorybookConfig } from 'storybook-react-rsbuild'

const config: StorybookConfig = {
  framework: 'storybook-react-rsbuild',
  stories: [],
  core: {
    builder: {
      name: 'storybook-builder-rsbuild',
      options: {
        // Path to your existing rsbuild.config.ts
        // Defaults to the root rsbuild.config.ts if found
        rsbuildConfigPath: './custom-rsbuild.config.ts',

        // Enable filesystem cache for faster rebuilds
        // Default: false
        fsCache: true,

        // Lazy-compile entries as well as dynamic imports
        // lazyCompilation: true,

        // Specify Rsbuild environment to use (for multi-environment configs)
        // environment: 'web',
      },
    },
  },
}

export default config
```

### 继承的 Rsbuild 配置

`rsbuildConfigPath` 选中的配置会自动合并到 Storybook preview 构建中。仅用于生产环境的设置可能影响或破坏 preview，因此不会继承以下字段：

- `source.entry`
- `output.distPath`、`output.filename`、`output.cleanDistPath`、`output.externals` 和 `output.assetPrefix`
- `server.publicDir`
- `dev.progressBar`、`dev.assetPrefix` 和 `dev.writeToDisk`
- `tools.htmlPlugin`
- `tools.rspack.output.library`、`tools.rspack.output.globalObject` 和 `tools.rspack.output.umdNamedDefine`

此边界也适用于从 `storybook-addon-rslib`、`storybook-addon-rstack` 和 `storybook-addon-modernjs` 继承的配置。`tools.rspack` 如果使用函数形式，内部字段将无法被检查和剥离。建议通过 `environment` 选择专用于 Storybook 的 [Rsbuild environment](https://rsbuild.rs/config/environments)。如果确实需要恢复某个已剥离的字段，请在 Storybook 的 `rsbuildFinal` 中显式添加；显式配置会在继承配置被剥离后执行。

Plugin 会继续继承，因为它们通常提供 preview build 所需的 transform。Storybook CLI 会在加载项目配置前将 `process.env.STORYBOOK` 设置为 `'true'`，可以用这个条件排除不应在 Storybook 中运行、仅供应用使用的 plugin。

### 选项参考

| Option              | Type                                                                               | Default                                               | Description                                                                        |
| :------------------ | :--------------------------------------------------------------------------------- | :---------------------------------------------------- | :--------------------------------------------------------------------------------- |
| `rsbuildConfigPath` | `string`                                                                           | `cwd/rsbuild.config.ts`                               | 待合并的已有 Rsbuild 配置文件路径。                                                             |
| `fsCache`           | `boolean`                                                                          | `false`                                               | 启用 Rspack 的持久化文件系统缓存。                                                              |
| `lazyCompilation`   | `boolean` \| [`LazyCompilationOptions`](https://rspack.rs/config/lazy-compilation) | `{ entries: false }`（development）；`false`（production） | 配置 Rspack 的 lazy compilation。                                                      |
| `environment`       | `string`                                                                           | `undefined`                                           | 从 Rsbuild 配置中选择 [environment](https://rsbuild.rs/config/environments)；显式指定的名称必须存在。 |

未指定 `environment` 时，没有 environment 则使用顶层配置，只有一个则自动选择，多个则必须指定名称。

在 development 中，默认值 `{ entries: false }` 会立即编译 entry chunk，同时对 dynamically imported story module 使用 lazy compilation。在 production 中，此 builder option 不会应用，因此 lazy compilation 默认保持关闭；底层 Rsbuild 或 Rspack 配置仍可覆盖该行为。在 development 中，自动检测到 MSW 也会将默认值改为 `false`，除非你显式配置此选项。这与 Storybook webpack builder 不同，后者的 lazy compilation 是 opt-in，除非显式启用，否则保持关闭。

## Webpack Addons 兼容性

由于 Rspack 兼容 webpack 的 loader/plugin API，你通常可以使用为 Webpack 设计的 Storybook addon。为此，请使用 `webpackAddons` 字段而非 `addons`。

```ts twoslash title=".storybook/main.ts"
// @noErrors
import type { StorybookConfig } from 'storybook-react-rsbuild'

const config: StorybookConfig = {
  framework: 'storybook-react-rsbuild',
  stories: [],
  // Addons that depend on Webpack loaders/plugins
  webpackAddons: ['@storybook/addon-coverage'],
}

export default config
```

## Framework 选项

framework 特有的选项让你能够为 React、Vue 等定制行为。

### React 选项

对于 `storybook-react-rsbuild`，你可以配置 `reactDocgen` 和 legacy root API。

```ts twoslash title=".storybook/main.ts"
// @noErrors
import type { StorybookConfig } from 'storybook-react-rsbuild'

const config: StorybookConfig = {
  framework: {
    name: 'storybook-react-rsbuild',
    options: {
      // Configure strict mode
      strictMode: true,

      // Use legacy ReactDOM.render instead of createRoot (React 18+)
      legacyRootApi: false,
    },
  },
  stories: [],
  typescript: {
    // Configure docgen for TypeScript
    // 'react-docgen-typescript' | 'react-docgen' | false
    reactDocgen: 'react-docgen-typescript',

    // Pass options to react-docgen-typescript-plugin
    reactDocgenTypescriptOptions: {
      propFilter: (prop) => {
        return prop.parent ? !/node_modules/.test(prop.parent.fileName) : true
      },
    },
  },
}

export default config
```

## TypeScript 选项

Storybook Rsbuild 使用 `@rsbuild/plugin-type-check` 进行类型检查。你可以通过 `typescript` 字段对其进行配置。

```ts twoslash title=".storybook/main.ts"
// @noErrors
import type { StorybookConfig } from 'storybook-react-rsbuild'

const config: StorybookConfig = {
  framework: 'storybook-react-rsbuild',
  stories: [],
  typescript: {
    // Enable/disable fork-ts-checker-webpack-plugin
    check: true,

    // Options passed to fork-ts-checker-webpack-plugin
    checkOptions: {
      typescript: {
        memoryLimit: 4096,
      },
    },
  },
}

export default config
```

通用的 TypeScript 配置请参阅 [Storybook TypeScript 文档](https://storybook.js.org/docs/configure/integration/typescript)。

## Preview 产物目录结构

`storybook build` 输出的 preview 产物采用扁平结构 —— 打包后的 JS 与 CSS 直接产出到输出目录（默认为 `storybook-static`），与官方 webpack5 builder 一致：

```text
storybook-static/
├── iframe.html
├── main.<hash>.iframe.bundle.js
├── <chunk-id>.<hash>.iframe.bundle.js
├── <entry>.<hash>.css
├── <name>.<hash>.svg      # 被引入的 SVG 与 WebAssembly 同样位于根目录
└── static/media/          # 被引入的图片、字体与媒体资源
```

v3.4.0 之前的版本会将这些文件嵌套在 `static/js/`、`static/js/async/` 和 `static/css/` 下。
