Docs
Storybook Docs

配置并与插件通信

插件 API 专为定制而设计。它为插件作者提供了不同的方式来配置和与用户的 Storybook 通信。让我们看看这些是什么以及它们的建议用例。

¥The addon API is designed for customization. It offers addon authors different ways to configure and communicate with their users' Storybook. Let's look at what these are and their suggested use cases.

预设

¥Preset

预设将配置负担从用户转移到插件。预设选项是全局的,可以从 NodeJS 访问。它们是预配置 Webpack 加载器、Babel 插件和其他库或框架特定配置的理想选择。

¥Presets offload the burden of configuration from the user to the addon. Preset options are global and are accessible from NodeJS. They're ideal for pre-configuring Webpack loaders, Babel plugins, and other library or framework-specific configurations.

例如,许多库要求应用由 Provider 封装,Provider 为树下的组件提供数据。预设可以描述自动添加封装器等行为,而无需用户进行任何手动配置。如果用户安装了具有预设的插件,则该插件可以指示 Storybook 将所有故事封装在 Provider 中。这允许人们开始使用你的库和 Storybook,只需 1 行配置!

¥For example, many libraries require that the app be wrapped by a Provider which provides data to components down the tree. Presets can describe behavior like adding wrappers automatically, without users having to do any manual configuration. If a user installs an addon that has Presets, the addon can instruct Storybook to wrap all stories in Provider. This allows folks to start using your library with Storybook, with just 1 line of config!

有关预设的更多信息,请参阅:编写预设插件

¥For more on presets, see: Write a preset addon

封装每个故事的机制称为 Storybook decorator。它们允许你使用额外的渲染功能或提供数据来扩充故事。

¥The mechanism for wrapping each story is referred to as a Storybook decorator. They allow you to augment stories with extra rendering functionality or by providing data.

参数

¥Parameters

参数在浏览器中可用,非常适合全局、组件级别或故事级别配置插件行为。

¥Parameters are available in the browser and are great for configuring addon behavior globally, at the component level, or at the story level.

例如,伪状态插件 使用参数来启用各种伪状态。用户可以提供全局默认值,然后在故事级别覆盖它们。

¥For example, the Pseudo States addon uses parameters to enable the various pseudo-states. Users can provide global defaults and then override them at the story level.

使用 useParameter 钩子访问插件中的参数值。

¥Use the useParameter hook to access the parameter values within your addon.

export const Hover = {
  render: () => <Button>Label</Button>,
  parameters: { pseudo: { hover: true } },
};

通道

¥Channels

通道使用与 NodeJS EventEmitter 兼容的 API 在管理器和预览窗格之间实现双向通信。你的插件可以插入特定通道并响应这些事件。

¥Channels enable two-way communication between the manager and the preview pane, using a NodeJS EventEmitter compatible API. Your addons can plug into specific channels and respond to these events.

例如,操作插件 捕获用户事件并在面板中显示其数据。

¥For example, the Actions addon captures user events and displays their data in a panel.

使用 useChannel 钩子访问插件中的通道数据。

¥Use the useChannel hook to access the channel data within your addon.

有关完整示例,请查看 storybookjs/addon-kit/withRoundTrip.ts

¥For a complete example, check out storybookjs/addon-kit/withRoundTrip.ts