Docs
Storybook Docs

使用 Vite 的 React Storybook

Storybook for React & Vite 是一个 framework,它可以轻松地为使用 Vite 构建的 React 应用单独开发和测试 UI 组件。

¥Storybook for React & Vite is a framework that makes it easy to develop and test UI components in isolation for React applications built with Vite.

安装

¥Install

要在现有的 React 项目中安装 Storybook,请在项目根目录下运行以下命令:

¥To install Storybook in an existing React project, run this command in your project's root directory:

npm create storybook@latest

接下来,你可以开始使用 写故事运行测试组件文档。要更好地控制安装过程,请参阅 安装指南

¥You can then get started writing stories, running tests and documenting your components. For more control over the installation process, refer to the installation guide.

要求

¥Requirements

  • React ≥ 16.8

  • Vite ≥ 5

运行 Storybook

¥Run Storybook

要为特定项目运行 Storybook,请运行以下命令:

¥To run Storybook for a particular project, run the following:

npm run storybook

要构建 Storybook,请运行:

¥To build Storybook, run:

npm run build-storybook

你将在配置的 outputDir(默认为 storybook-static)中找到输出。

¥You will find the output in the configured outputDir (default is storybook-static).

常见问题

¥FAQ

如何从 React Webpack 框架迁移?

¥How do I migrate from the React Webpack framework?

运行 upgrade 命令时,应该会提示你迁移到 @storybook/react-vite

¥The upgrade command should prompt you to migrate to @storybook/react-vite when you run it:

npx storybook@latest upgrade

如果自动迁移对你的项目不起作用,请参阅下面的手动安装说明。

¥In case that auto-migration does not work for your project, refer to the manual installation instructions below.

如何手动安装 React 框架?

¥How do I manually install the React framework?

首先,安装框架:

¥First, install the framework:

npm install --save-dev @storybook/react-vite

然后,更新你的 .storybook/main.js|ts 以更改框架属性:

¥Then, update your .storybook/main.js|ts to change the framework property:

.storybook/main.ts
import type { StorybookConfig } from '@storybook/react-vite';
 
const config: StorybookConfig = {
  // ...
  // framework: '@storybook/react-webpack5', 👈 Remove this
  framework: '@storybook/react-vite', // 👈 Add this
};
 
export default config;

API

选项

¥Options

如果需要,你可以传递一个选项对象以进行其他配置:

¥You can pass an options object for additional configuration if needed:

.storybook/main.ts
import type { StorybookConfig } from '@storybook/react-vite';
 
const config: StorybookConfig = {
  framework: {
    name: '@storybook/react-vite',
    options: {
      // ...
    },
  },
};
 
export default config;

builder

类型:Record<string, any>

¥Type: Record<string, any>

配置 框架的构建器 的选项。对于此框架,可以在 Vite 构建器文档 中找到可用选项。

¥Configure options for the framework's builder. For this framework, available options can be found in the Vite builder docs.