For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt, and this page is available as Markdown at /zh/guide/framework/web-components.md.
close

Web Components

storybook-web-components-rsbuild 使用 Storybook 和 Rsbuild 构建 Lit 与标准 Custom Elements 的组件 stories。完整示例可参考 Lit sandbox。

环境要求

要求版本
Node.js>= 22.12.0
lit^2.0.0 或 ^3.0.0
@rsbuild/core^2.0.0
storybook^11.0.0
typescript^5.9.0 || ^6.0.0 || ^7.0.0

安装与配置

安装 storybook-web-components-rsbuild 和 @rsbuild/core:

npm
yarn
pnpm
bun
deno
npm install @rsbuild/core storybook-web-components-rsbuild -D

配置 .storybook/main.ts:

.storybook/main.ts
import type { 
import StorybookConfig
StorybookConfig
} from 'storybook-web-components-rsbuild'
const
const config: StorybookConfig
config
:
import StorybookConfig
StorybookConfig
= {
framework: string
framework
: 'storybook-web-components-rsbuild',
stories: string[]
stories
: ['../src/**/*.stories.@(js|mjs|ts)'],
} export default
const config: StorybookConfig
config

通用的 main.ts 配置和 CSF 用法请参阅 Storybook Configure 和 Writing Stories。

配置

在 .storybook/main.ts 中配置 framework.options:

builder

  • 类型: BuilderOptions
  • 默认值: {}

传递给 storybook-builder-rsbuild 的选项。请参阅 core.builder.options。

customElementsManifest

  • 类型: string | string[]
  • 默认值: undefined

Custom Elements Manifest 文件路径,相对于 .storybook/ 解析。未设置时回退读取最近 package.json 中的 customElements 字段。

.storybook/main.ts
import type { 
import StorybookConfig
StorybookConfig
} from 'storybook-web-components-rsbuild'
const
const config: StorybookConfig
config
:
import StorybookConfig
StorybookConfig
= {
framework: {
    name: string;
    options: {
        customElementsManifest: string;
    };
}
framework
: {
name: string
name
: 'storybook-web-components-rsbuild',
options: {
    customElementsManifest: string;
}
options
: {
customElementsManifest: string
customElementsManifest
: '../custom-elements.json',
}, },
stories: string[]
stories
: ['../src/**/*.stories.@(js|mjs|ts)'],
} export default
const config: StorybookConfig
config

Framework 行为

Custom Elements Manifest 与 docgen

只要 customElementsManifest(或 package.json 中的 customElements)成功解析出 manifest(即使未安装 TypeScript),或者项目安装了兼容的 TypeScript 版本,Storybook 就会默认启用 features.docgenServer,详见 Storybook TypeScript Integration。未在 manifest 中声明的 custom elements 会直接从源码进行分析。customElementsManifest 取代了已废弃的运行时辅助函数 setCustomElementsManifest(将在 Storybook 12 中移除)。

剥离继承的 HTML 配置

storybook-web-components-rsbuild 会在自身的 rsbuildFinal hook 中删除从 rsbuild.config.ts 继承的 config.html,以防止应用的 HTML 模板(如自定义 html.template)污染 Storybook 的 preview iframe。如有需要作用于 preview 的 html 自定义配置,请在随后执行的 .storybook/main.ts rsbuildFinal 中设置。