Docs
Storybook Docs

自动文档和 Storybook

Watch a video tutorial

Storybook Autodocs 是一个功能强大的工具,可以帮助你快速为 UI 组件生成全面的文档。通过利用 Autodocs,你可以将故事转换为动态文档,可以使用 MDX文档块 进一步扩展,以提供对组件功能的清晰简洁的理解。

¥Storybook Autodocs is a powerful tool that can help you quickly generate comprehensive documentation for your UI components. By leveraging Autodocs, you're transforming your stories into living documentation which can be further extended with MDX and Doc Blocks to provide a clear and concise understanding of your components' functionality.

Storybook 推断相关元数据(例如 argsargTypesparameters)并自动生成一个文档页面,此信息位于侧边栏中组件树的根级别。

¥Storybook infers the relevant metadata (e.g., args, argTypes, parameters) and automatically generates a documentation page with this information positioned at the root-level of your component tree in the sidebar.

Storybook autodocs

设置自动文档

¥Set up automated documentation

Autodocs 通过 tags 配置。如果 CSF 文件包含至少一个标有 autodocs 的故事,则会为该组件生成文档页面。

¥Autodocs is configured through tags. If a CSF file contains at least one story tagged with autodocs, then a documentation page will be generated for that component.

要为项目中的所有故事启用自动文档,请将其添加到 .storybook/preview.js|ts 文件中的 tags

¥To enable automatic documentation for all stories in a project, add it to tags in your .storybook/preview.js|ts file:

.storybook/preview.ts
// Replace your-renderer with the renderer you are using (e.g., react, vue3)
import type { Preview } from '@storybook/your-renderer';
 
const preview: Preview = {
  // ...rest of preview
  //👇 Enables auto-generated documentation for all stories
  tags: ['autodocs'],
};
 
export default preview;

你还可以在组件(或故事)级别启用它:

¥You can also enable it at the component (or story) level:

Button.stories.ts
// Replace your-framework with the framework you are using (e.g., nextjs, vue3-vite)
import type { Meta } from '@storybook/your-framework';
 
import { Button } from './Button';
 
const meta: Meta<typeof Button> = {
  component: Button,
  //👇 Enables auto-generated documentation for this component and includes all stories in this file
  tags: ['autodocs'],
};
export default meta;

你可以通过 删除标签 禁用特定组件的自动文档:

¥You can disable auto docs for a particular component by removing the tag:

Page.stories.ts
// Replace your-framework with the framework you are using (e.g., nextjs, vue3-vite)
import type { Meta, StoryObj } from '@storybook/your-framework';
 
import { Page } from './Page';
 
const meta: Meta<typeof Page> = {
  component: Page,
  // 👇 Disable auto-generated documentation for this component
  tags: ['!autodocs'],
};
export default meta;

同样,你可以通过删除标签从自动文档页面中排除特定的故事:

¥Similarly, you can exclude a particular story from the auto docs page, by removing the tag:

Button.stories.ts
// Replace your-framework with the framework you are using (e.g., nextjs, vue3-vite)
import type { Meta, StoryObj } from '@storybook/your-framework';
 
import { Button } from './Button';
 
const meta: Meta<typeof Button> = {
  component: Button,
  //👇 Enables auto-generated documentation for this component and includes all stories in this file
  tags: ['autodocs'],
};
export default meta;
 
type Story = StoryObj<typeof Button>;
 
export const UndocumentedStory: Story = {
  // 👇 Removes this story from auto-generated documentation
  tags: ['!autodocs'],
};

配置

¥Configure

除了使用 tags 启用该功能外,你还可以扩展 Storybook 配置文件(即 .storybook/main.js|ts|cjs)并提供其他选项来控制如何创建文档。下面列出了可用的选项及其使用方法示例。

¥In addition to enabling the feature with tags, you can extend your Storybook configuration file (i.e., .storybook/main.js|ts|cjs) and provide additional options to control how documentation gets created. Listed below are the available options and examples of how to use them.

.storybook/main.ts
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
 
const config: StorybookConfig = {
  framework: '@storybook/your-framework',
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  addons: ['@storybook/addon-essentials'],
  docs: {
    //👇 See the table below for the list of supported options
    defaultName: 'Documentation',
  },
};
 
export default config;
选项描述
defaultName将自动生成的文档页面重命名为
默认:docs: { defaultName: 'Documentation' }

编写自定义模板

¥Write a custom template

Watch a video tutorial

要替换 Storybook 使用的默认文档模板,你可以扩展 UI 配置文件(即 .storybook/preview.js|ts)并引入 docs 参数。此参数接受返回 React 组件的 page 函数,你可以使用该组件生成所需的模板。例如:

¥To replace the default documentation template used by Storybook, you can extend your UI configuration file (i.e., .storybook/preview.js|ts) and introduce a docs parameter. This parameter accepts a page function that returns a React component, which you can use to generate the required template. For example:

.storybook/preview.tsx
// Replace your-framework with the framework you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-framework';
 
import { Title, Subtitle, Description, Primary, Controls, Stories } from '@storybook/blocks';
 
const preview: Preview = {
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
    docs: {
      page: () => (
        <>
          <Title />
          <Subtitle />
          <Description />
          <Primary />
          <Controls />
          <Stories />
        </>
      ),
    },
  },
};
 
export default preview;

在内部,Storybook 使用类似的实现来生成默认模板。有关 Doc Blocks 如何工作,请参阅 Doc Blocks API 参考

¥Internally, Storybook uses a similar implementation to generate the default template. See the Doc Blocks API reference to learn more about how Doc Blocks work.

更详细地介绍代码片段。当 Storybook 启动时,它将用由以下内容组成的自定义模板覆盖默认模板:

¥Going over the code snippet in more detail. When Storybook starts up, it will override the default template with the custom one composed of the following:

  1. 标题,其中包含由 TitleSubtitleDescription 文档块检索的组件元数据。

    ¥A header with the component's metadata retrieved by the Title, Subtitle, and Description Doc Blocks.

  2. 文件中通过 Primary Doc Block 定义的第一个故事,带有一组方便的 UI 控件来放大和缩小组件。

    ¥The first story defined in the file via the Primary Doc Block with a handy set of UI controls to zoom in and out of the component.

  3. 通过 Controls Doc Block 在故事中定义的所有相关 argsargTypes 的交互式表格。

    ¥An interactive table with all the relevant args and argTypes defined in the story via the Controls Doc Block.

  4. 通过 Stories Doc Block 概览剩余的故事。

    ¥A overview of the remaining stories via the Stories Doc Block.

使用 MDX

¥With MDX

你还可以使用 MDX 生成文档模板。这在未配置 JSX 处理的非 React 项目中很有用。通常,当你在项目中创建 MDX 文件时,它会被视为普通文档。要表明 MDX 文件是文档模板,请将 isTemplate 属性提供给其 Meta Doc Block。例如:

¥You can also use MDX to generate the documentation template. This is useful in non-React projects where JSX-handling is not configured. Normally, when you create an MDX file in your project, it is treated as normal documentation. To indicate that an MDX file is a documentation template, supply the isTemplate property to its Meta Doc Block. For example:

{/* DocumentationTemplate.mdx */}
 
import { Meta, Title, Primary, Controls, Stories } from '@storybook/blocks';
 
{/* 
  * 👇 The isTemplate property is required to tell Storybook that this is a template
  * See https://storybook.js.org/docs/api/doc-blocks/doc-block-meta
  * to learn how to use
*/}
 
<Meta isTemplate />
 
<Title />
 
# Default implementation
 
<Primary />
 
## Inputs
 
The component accepts the following inputs (props):
 
<Controls />
 
---
 
## Additional variations
 
Listed below are additional variations of the component.
 
<Stories />
 

然后你可以通过导入它在你的 .storybook/preview.js 或单个故事文件中使用它:

¥Then you can use it in your .storybook/preview.js or an individual story file by importing it:

.storybook/preview.jsx
import DocumentationTemplate from './DocumentationTemplate.mdx';
 
export default {
  parameters: {
    docs: {
      page: DocumentationTemplate,
    },
  },
};

如果你只需要覆盖单个组件的文档页面,我们建议创建一个 MDX 文件并通过 <Meta of={} /> Doc Block 直接引用它。

¥If you only need to override the documentation page for a single component, we recommend creating an MDX file and referencing it directly via the <Meta of={} /> Doc Block.

生成目录

¥Generate a table of contents

Storybook 自动生成的文档页面可能很长且难以浏览。为了解决此问题,你可以启用目录功能以快速概览文档页面并允许用户跳转到特定部分。要启用它,请扩展你的 Storybook UI 配置文件(即 .storybook/preview.js)并提供具有 toc 属性的 docs 参数

¥Storybook's auto-generated documentation pages can be quite long and difficult to navigate. To help with this, you can enable the table of contents feature to provide a quick overview of the documentation page and allow users to jump to a specific section. To enable it, extend your Storybook UI configuration file (i.e., .storybook/preview.js) and provide a docs parameter with a toc property.

.storybook/preview.ts
// Replace your-framework with the framework you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-framework';
 
const preview: Preview = {
  parameters: {
    docs: {
      toc: true, // 👈 Enables the table of contents
    },
  },
};
 
export default preview;

配置目录

¥Configure the table of contents

默认情况下,文档页面上的目录将仅显示自动生成的 h3 标题。但是,如果你想自定义目录,你可以向 toc 属性添加更多参数。以下选项及其使用示例可用。

¥By default, the table of contents on the documentation page will only show the h3 headings that are automatically generated. However, if you want to customize the table of contents, you can add more parameters to the toc property. The following options and examples of how to use them are available.

选项描述
contentsSelector定义用于搜索标题
toc: { contentsSelector: '.sbdocs-content' } 的容器 CSS 选择器
disable隐藏文档页面
toc: { disable: true } 的目录
headingSelector定义目录中要显示的标题列表
toc: { headingSelector: 'h1, h2, h3' }
ignoreSelector配置目录以忽略特定标题或故事。默认情况下,目录将忽略放置在 Story 块
toc: { ignoreSelector: '.docs-story h2' } 内的所有内容
title定义目录的标题。 接受以下之一:stringnull、React 元素
toc: { title: 'Table of Contents' }
unsafeTocbotOptions提供额外的 TocBot 配置选项
toc: { unsafeTocbotOptions: { orderedList: true } }

contentsSelectorheadingSelectorignoreSelector 属性允许进行额外的自定义。有关使用它们的更多信息,请参阅 Tocbot 文档

¥The contentsSelector, headingSelector, and ignoreSelector properties allow additional customization. For more information on using them, see the Tocbot documentation.

.storybook/preview.ts
// Replace your-framework with the framework you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-framework';
 
const preview: Preview = {
  parameters: {
    docs: {
      toc: {
        contentsSelector: '.sbdocs-content',
        headingSelector: 'h1, h2, h3',
        ignoreSelector: '#primary',
        title: 'Table of Contents',
        disable: false,
        unsafeTocbotOptions: {
          orderedList: false,
        },
      },
    },
  },
};
 
export default preview;

组件级配置

¥Component-level configuration

如果你想自定义特定故事的目录,你可以在故事的默认导出中包含 toc 属性并提供所需的 configuration。例如,如果你需要隐藏特定故事的目录,请按如下方式调整你的故事:

¥If you want to customize the table of contents for a specific story, you can include a toc property in the story's default export and provide the required configuration. For example, if you need to hide the table of contents for a specific story, adjust your story as follows:

MyComponent.stories.ts|tsx
// Replace your-framework with the name of your framework
import type { Meta } from '@storybook/your-framework';
 
import { MyComponent } from './MyComponent';
 
const meta: Meta<typeof MyComponent> = {
  component: MyComponent,
  tags: ['autodocs'],
  parameters: {
    docs: {
      toc: {
        disable: true, // 👈 Disables the table of contents
      },
    },
  },
};
 
export default meta;

自定义组件文档

¥Customize component documentation

使用 Storybook 的 Autodocs 创建自动文档为你提供了构建可持续文档模式的起点。但是,它可能并不适合每种情况,你可能希望扩展它并提供更多信息。对于这种情况,我们建议将 MDX 与 Storybook 的 文档块 结合起来编写文档。

¥Creating automated documentation with Storybook's Autodocs provides you with the starting point to build a sustainable documentation pattern. Nevertheless, it may not be suited for every case, and you may want to extend it and provide additional information. We recommend combining MDX alongside Storybook's Doc Blocks for such cases to author your documentation.

高级配置

¥Advanced configuration

记录多个组件

¥Documenting multiple components

有时将多个组件一起记录会很有帮助。例如,组件库的 ButtonGroup 和 Button 组件如果没有彼此,可能就没有意义。

¥Sometimes it's helpful to document multiple components together. For example, a component library’s ButtonGroup and Button components might not make sense without one another.

Autodocs 允许你记录由 component 属性定义的 "main" 组件以及与其相关的一个或多个 subcomponents

¥Autodocs allows you to document your "main" component, defined by the component property, as well as one or more subcomponents related to it.

List.stories.ts|tsx
import React from 'react';
import type { Meta, StoryObj } from '@storybook/react';
 
import { List } from './List';
import { ListItem } from './ListItem';
 
const meta: Meta<typeof List> = {
  component: List,
  subcomponents: { ListItem }, //👈 Adds the ListItem component as a subcomponent
};
export default meta;
 
type Story = StoryObj<typeof List>;
 
export const Empty: Story = {};
 
export const OneItem: Story = {
  render: (args) => (
    <List {...args}>
      <ListItem />
    </List>
  ),
};

Subcomponents in ArgTypes doc block

主要组件及其子组件将显示在 ArgTypes 文档块 的选项卡式版本中。选项卡标题将对应于 subcomponents 对象的键。

¥The main component and its subcomponents will show up in a tabbed version of the ArgTypes doc block. The tab titles will correspond to the keys of the subcomponents object.

如果你想以不同的方式为组件组组织文档,我们推荐 使用 MDX。它让你完全控制组件的显示方式并支持任何配置。

¥If you want to organize your documentation differently for component groups, we recommend using MDX. It gives you complete control over how your components are displayed and supports any configuration.

自定义文档容器

¥Customize the Docs Container

Docs Container 是封装文档页面的组件。它负责在 Storybook 的 UI 中渲染文档页面。你可以通过创建自己的组件并更新 Storybook UI 配置文件(即 .storybook/preview.js)来引用它,从而对其进行自定义。

¥The Docs Container is the component that wraps up the documentation page. It's responsible for rendering the documentation page in Storybook's UI. You can customize it by creating your own component and updating your Storybook UI configuration file (i.e., .storybook/preview.js) to reference it.

.storybook/preview.ts
import * as React from 'react';
 
// Replace your-framework with the framework you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-framework';
 
import { DocsContainer } from '@storybook/blocks';
 
const ExampleContainer = ({ children, ...props }) => {
  return <DocsContainer {...props}>{children}</DocsContainer>;
};
 
const preview: Preview = {
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
    docs: {
      container: ExampleContainer,
    },
  },
};
 
export default preview;

覆盖默认主题

¥Override the default theme

默认情况下,Storybook 为 UI 提供了两个主题:lightdark。如果你需要自定义文档使用的主题以匹配现有主题,你可以更新 Storybook UI 配置文件(即 .storybook/preview.js)并应用它。

¥By default, Storybook provides two themes for the UI: light and dark. If you need to customize the theme used by the documentation to match the existing one, you can update your Storybook UI configuration file (i.e., .storybook/preview.js) and apply it.

.storybook/preview.ts
// Replace your-framework with the framework you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-framework';
 
import { themes, ensure } from '@storybook/theming';
 
const preview: Preview = {
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
    docs: {
      theme: ensure(themes.dark), // The replacement theme to use
    },
  },
};
 
export default preview;

使用自定义 MDX 组件

¥Working with custom MDX components

开箱即用,Storybook 有一组组件,你可以使用它们来自定义文档页面。如果你正在使用设计系统或组件库并希望将它们添加到你的文档页面,则可以使用你自己的组件覆盖从 @mdx-js/react 继承的 MDXProvider 组件。但是,有一个警告,组件替换仅在你使用 Markdown 语法编写文档时才会产生影响(例如,标题为 #)。原生 HTML 元素(例如 <h1>)不会被你的自定义实现替换。

¥Out of the box, Storybook has a set of components that you can use to customize your documentation page. If you're working with a design system or component library and wish to add them to your documentation page, you can override the MDXProvider component inherited from @mdx-js/react with your own. However, there's a caveat to this, the component replacement will only have an impact if you're writing documentation using Markdown syntax (e.g., # for headings). Native HTML elements, such as <h1>, will not be replaced with your custom implementation.

.storybook/preview.ts
// Replace your-framework with the framework you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-framework';
 
import { MDXProvider } from '@mdx-js/react';
 
import { DocsContainer } from '@storybook/blocks';
 
import * as DesignSystem from 'your-design-system';
 
export const MyDocsContainer = (props) => (
  <MDXProvider
    components={{
      h1: DesignSystem.H1,
      h2: DesignSystem.H2,
    }}
  >
    <DocsContainer {...props} />
  </MDXProvider>
);
 
const preview: Preview = {
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
    docs: {
      container: MyDocsContainer,
    },
  },
};
 
export default preview;

这不是 Storybook 问题,而是 MDX 工作方式的细节。来自他们的 迁移指南

¥This is not a Storybook issue but a detail of how MDX works. From their migration guide:

“由于缺乏更好的名称,我们现在‘沙盒’组件。这意味着当你为 h1 传递一个组件时,它会用于 # hi,但不会用于 <h1>hi</h1>

¥“We now ‘sandbox’ components, for lack of a better name. It means that when you pass a component for h1, it does get used for # hi but not for <h1>hi</h1>

故障排除

¥Troubleshooting

目录未按预期渲染

¥The table of contents doesn't render as expected

使用 Autodocs 的目录时,你可能会遇到与预期不同的情况。为了帮助你解决这些问题,我们编制了一份可能导致问题的可能情况列表。

¥When using Autodocs's table of contents, you may encounter situations where it appears differently than expected. To help you resolve these problems, we have compiled a list of possible scenarios that may cause issues.

使用简单文档页面

¥With simple documentation pages

如果你的文档页面只有一个匹配的标题并为其创建目录,则默认情况下不会隐藏目录。此问题的潜在解决方案是添加第二个标题或完全关闭它。

¥If you have a documentation page with only one matching heading and create a table of contents for it, the table of contents will not be hidden by default. A potential solution for this issue would be to add a second heading or turn it off entirely.

使用小屏幕

¥With small screens

如果屏幕宽度小于 1200px,则目录将默认隐藏。目前,没有针对此问题的内置解决方案,不会影响文档页面的样式兼容性。

¥If the screen width is less than 1200px, the table of contents will be hidden by default. Currently, there's no built-in solution for this issue that doesn't impact the documentation page's style compatibility.

使用 MDX

¥With MDX

如果你使用 MDX 编写 未附加的文档,则无法自定义目录,这主要是因为缺乏基于当前实现定义参数的支持。因此,目录将始终恢复为全局提供的默认 configuration

¥If you're writing unattached documentation using MDX, you cannot customize the table of contents primarily due to the lack of support for defining parameters based on the current implementation. As a result, the table of contents will always revert to the default configuration provided globally.

自动生成的文档未显示在 monorepo 设置

¥The auto-generated documentation is not showing up in a monorepo setup

开箱即用,Storybook 的 Autodocs 功能旨在自动为你的故事生成文档。但是,如果你使用的是 monorepo 设置(例如 Yarn Workspacespnpm Workspaces),你可能会遇到无法为你生成部分文档的问题。为了帮助你解决这些问题,我们准备了一些可能对你有帮助的建议。

¥Out of the box, Storybook's Autodocs feature is built to generate documentation for your stories automatically. Nevertheless, if you're working with a monorepo setup (e.g., Yarn Workspaces, pnpm Workspaces), you may run into issues where part of the documentation may not be generated for you. To help you troubleshoot those issues, we've prepared some recommendations that might help you.

更新你的导入语句以直接引用组件而不是包的根。例如:

¥Update your import statements to reference the component directly instead of the package's root. For example:

MyComponent.stories.ts|tsx
// Replace your-framework with the name of your framework
import type { Meta } from '@storybook/your-framework';
 
// ❌ Don't use the package's index file to import the component.
import { MyComponent } from '@component-package';
 
// ✅ Use the component's export to import it directly.
import { MyComponent } from '@component-package/src/MyComponent';
 
const meta: Meta<typeof MyComponent> = {
  /* 👇 The title prop is optional.
   * See https://storybook.js.org/docs/configure/#configure-story-loading
   * to learn how to generate automatic titles
   */
  title: 'MyComponent',
  component: MyComponent,
};
 
export default meta;

此外,如果你使用 TypeScript 进行开发,则可能需要更新 Storybook 的配置文件(即 .storybook/main.js|ts)以包含以下内容:

¥Additionally, if you're developing using TypeScript, you may need to update Storybook's configuration file (i.e., .storybook/main.js|ts) to include the following:

.storybook/main.ts
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
 
const config: StorybookConfig = {
  framework: '@storybook/your-framework',
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  typescript: {
    // Overrides the default Typescript configuration to allow multi-package components to be documented via Autodocs.
    reactDocgen: 'react-docgen',
    check: false,
  },
};
 
export default config;

如果你仍然遇到问题,我们建议你使用默认沟通渠道(例如 GitHub 讨论)联系社区。

¥If you're still encountering issues, we recommend reaching out to the community using the default communication channels (e.g., GitHub discussions).

控件未更新自动生成的文档中的故事

¥The controls are not updating the story within the auto-generated documentation

如果你通过 inline 配置选项关闭了故事的内联渲染,你将遇到相关控件未在文档页面中更新故事的情况。这是当前实现的已知限制,将在未来的版本中解决。

¥If you turned off inline rendering for your stories via the inline configuration option, you would run into a situation where the associated controls are not updating the story within the documentation page. This is a known limitation of the current implementation and will be addressed in a future release.

了解有关 Storybook 文档的更多信息

¥Learn more about Storybook documentation

  • 用于为你的故事创建文档的 Autodocs

    ¥Autodocs for creating documentation for your stories

  • MDX 用于自定义你的文档

    ¥MDX for customizing your documentation

  • 文档块 用于编写你的文档

    ¥Doc Blocks for authoring your documentation

  • 发布文档 用于自动化发布文档的过程

    ¥Publishing docs to automate the process of publishing your documentation