Bootstrap

Storybook-UI组件的开发环境

Why StoryBook? 为什么使用 StoryBook ?

The web’s universality is pushing more complexity into the frontend. Over time, additional requirements piled on like devices, browsers, accessibility, performance, and async states.

网络的普遍性正在让前端越来越复杂,随着时间的推移,设备、浏览器、可访问性、性能和异步状态等附加需求不断增加。

Component-driven tools like React, Vue, and Angular help break down complex UIs into simple components but they’re not silver bullets. As frontends grow, the number of components swells. Mature projects can contain hundreds of components that yield thousands of discrete variations.

React、Vue和Angular等组件驱动工具有助于将复杂的UI分解为简单的组件,但它们不是银弹。随着前端的增长,组件的数量也会增加。成熟的项目可以包含数百个组件,产生数千个离散的变体。

The web’s universality is pushing more complexity into the frontend. It began with responsive web design, which turned every user interface from one to 10, 100, 1000 different user interfaces. Over time, additional requirements piled on like devices, browsers, accessibility, performance, and async states.
更为复杂的是,这些UI调试起来很痛苦,因为它们与业务逻辑、交互状态和应用程序上下文纠缠在一起。

The web’s universality is pushing more complexity into the frontend. It began with responsive web design, which turned every user interface from one to 10, 100, 1000 different user interfaces. Over time, additional requirements piled on like devices, browsers, accessibility, performance, and async states.
现代前端的广度压倒了现有的工作流程。开发人员必须考虑无数的UI变体,但还没有能力开发或组织所有这些变体。你最终会遇到这样的情况:UI更难构建,工作起来不那么令人满意,而且很脆弱。

UI multiverse

The Solution 

Build UIs in isolation 独立构建UI

Every piece of UI is now a component. The superpower of components is that you don't need to spin up the whole app just to see how they render. You can render a specific variation in isolation by passing in props, mocking data, or faking events.

现在,每一个UI都是一个组件。组件的超能力在于,你不需要旋转整个应用程序来查看它们是如何渲染的。您可以通过传递props、模拟数据或伪造事件来孤立地呈现特定的变体。

Storybook is packaged as a small, development-only, workshop that lives alongside your app. It provides an isolated iframe to render components without interference from app business logic and context. That helps you focus development on each variation of a component, even the hard-to-reach edge cases。

StoryBook被打包为一个小型的、仅用于开发的研讨会,与您的应用程序一起使用。它提供了一个独立的iframe来呈现组件,而不受应用程序业务逻辑和上下文的干扰。这有助于您将开发重点放在组件的每个变体上,甚至是难以触及的边缘案例。 

Capture UI variations as “stories” 将UI变量捕获为“故事”

When developing a component variation in isolation, save it as a story. Stories are a declarative syntax for supplying props and mock data to simulate component variations. Each component can have multiple stories. Each story allows you to demonstrate a specific variation of that component to verify appearance and behavior

当单独开发组件变体时,将其另存为 story。Stories是一种声明性语法,用于提供道具和模拟数据来模拟组件变体。每个组件可以有多个故事。每个故事都允许您演示该组件的特定变体,以验证外观和行为。

You write stories for granular UI component variation and then use those stories in development, testing, and documentation.

您为细粒度的UI组件变体编写 story ,然后在开发、测试和文档中使用这些故事。

import pinDialog from '../components/pin-dialog/pin-dialog.vue';


// More on how to set up stories at: https://storybook.js.org/docs/writing-stories
export default {
  title: 'Example/pinDialog',
  component: pinDialog,
  tags: ['autodocs'],
  render: (args, { argTypes }) => ({
    props: [
      ...Object.keys(argTypes)
    ],
    components: { pinDialog },
    template: '<pin-dialog v-bind="$props"></pin-dialog>',
  }),
  argTypes: {
  },
};

// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const visible = {
  args: {
    pinDialog: {
      visible: true
    }
  },
};

Storybook keeps track of every story - Storybook 记录每一个故事

Storybook is an interactive directory of your UI components and their stories. In the past, you'd have to spin up the app, navigate to a page, and contort the UI into the right state. This is a huge waste of time and bogs down frontend development. With Storybook, you can skip all those steps and jump straight to working on a UI component in a specific state.

Storybook 是UI组件及其故事的交互式目录。在过去,你必须启动应用程序,导航到一个页面,然后将UI控制到正确的状态。这是对时间的巨大浪费,阻碍了前端开发。使用Storybook,您可以跳过所有这些步骤,直接跳到特定状态下的UI组件上。

Where does Storybook fit into my project?

Storybook is packaged as a small, development-only, workshop that lives alongside your app. Install it by running a command.

故事书被打包为一个小型的、仅用于开发的研讨会,与您的应用程序一起使用。通过运行命令进行安装。

During development, run it in a separate node process. If you’re working on UI in isolation, the only thing you’ll need to run is Storybook.

在开发过程中,在单独的节点进程中运行它。如果你在孤立地处理UI,你唯一需要运行的就是Storybook。

Does Storybook work with my favorite libraries?

Storybook aims to integrate with industry-standard tools and platforms to simplify setup. Thanks to our ambitious developer community, we’ve made significant progress. There are hundreds of addons and tutorials that walk through how to set up Storybook in all types of projects.

Storybook 旨在与行业标准工具和平台集成,以简化设置。由于我们雄心勃勃的开发人员社区,我们取得了重大进展。有数百个插件和教程,介绍如何在所有类型的项目中设置故事书。

If you’re using a niche framework or a recently launched tool, we might not have an integration for it yet. Consider creating a proof of concept yourself first to lead the way for the rest of the community.

如果您使用的是利基框架或最近推出的工具,我们可能还没有对其进行集成。考虑先自己创建一个概念验证,为社区其他成员带路。

What’s the recommended Storybook workflow?

Every team is different and so is their workflow. Storybook is designed to be incrementally adoptable. Teams can gradually try features to see what works best for them

每个团队都是不同的,他们的工作流程也是不同的。Storybook 的设计是为了逐渐被采用。团队可以逐步尝试功能,看看什么最适合他们。

Most community members choose a Component-Driven workflow. UIs are developed in isolation from the “bottom up” starting with basic components then progressively combined to assemble pages.

大多数社区成员选择“组件驱动”工作流。UI是独立于“自下而上”开发的,从基本组件开始,然后逐步组合以组装页面。

  • Build each component in isolation and write stories for its variations.
    单独构建每个组件,并为其变体编写故事。
  • Compose small components together to enable more complex functionality.
    将小组件组合在一起以实现更复杂的功能。

  • Assemble pages by combining composite components.

    通过组合复合组件来组装页面。

  • Integrate pages into your project by hooking up data and business logic.

    通过连接数据和业务逻辑,将页面集成到项目中。

Benefits

When you write stories for components, you get a bunch of additional benefits for free.

当你为组件编写 Story 时,你会免费获得一系列额外的好处。

Develop UIs that are more durable  开发更耐用的UI

Isolate components and pages and track their use cases as stories. Verify hard-to-reach edge cases of UI. Use addons to mock everything a component needs—context, API requests, device features, etc.

隔离组件和页面,并将它们的用例作为 Story 进行跟踪。验证用户界面难以触及的边缘情况。使用插件来模拟组件所需的一切——上下文、API请求、设备功能等。

Test UIs with less effort and no flakes  用更少的精力测试UI,而且不会出现任何问题

Stories are a pragmatic, reproducible way of tracking UI states. Use them to spot-test the UI during development. Storybook offers built-in workflows for automated AccessibilityInteraction, and Visual testing. Or use stories as test cases by importing them into other JavaScript testing tools.

Stories 是一种实用的、可复制的跟踪UI状态的方法。在开发过程中使用它们对UI进行点测试。Storybook 提供了用于自动辅助功能、交互和可视化测试的内置工作流。或者通过将 Story 导入其他JavaScript测试工具,将它们用作测试用例。

Document UI for your team to reuse 文档UI供您的团队重复使用

Storybook is the single source of truth for your UI. Stories index all your components and their various states, making it easy for your team to find and reuse existing UI patterns. Storybook also auto-generates documentation from those stories.

Storybook 是UI真实性的唯一来源。Stories为您的所有组件及其各种状态建立索引,使您的团队能够轻松地查找和重用现有的UI模式。Storybook 还可以根据这些故事自动生成文档。

Share how the UI actually works  分享UI的实际工作方式

Stories show how UIs actually work, not just a picture of how they're supposed to work. That keeps everyone aligned on what's currently in production. Publish Storybook to get sign-off from teammates. Or embed them in wikis, Markdown, and Figma to streamline collaboration.

Story 展示了UI的实际工作方式,而不仅仅是它们应该如何工作的画面。这使每个人都能对目前正在生产的产品保持一致。发布 Storybook 以获得队友的批准。或者将它们嵌入到 Wiki、Markdown 和 Figma 中,以简化协作。

Automate UI workflows 自动化UI工作流

Storybook is compatible with your continuous integration workflow. Add it as a CI step to automate user interface testing, review implementation with teammates, and get signoff from stakeholders.

Storybook 与您的持续集成工作流兼容。将其添加为CI步骤,以自动化用户界面测试,与队友一起审查实施情况,并获得利益相关者的批准。

安装与使用

Install

Use the Storybook CLI to install it in a single command. Run this inside your existing project’s root directory:

使用Storybook CLI在单个命令中进行安装。在现有项目的根目录中运行此操作:

pnpm dlx storybook@latest init

storybook init is not made for empty projects

storybook init 不是为空项目制作的

Storybook needs to be installed into a project that is already set up with a framework. It will not work on an empty project. There are many ways to bootstrap an app in a given framework, including:

需要安装到已经使用框架设置的项目中。它在一个空项目上不起作用。有许多方法可以在给定的框架中引导应用程序,包括:

Storybook will look into your project's dependencies during its install process and provide you with the best configuration available.

Storybook 将在项目安装过程中查看项目的依赖关系,并为您提供可用的最佳配置。

The command above will make the following changes to your local environment:

上面的命令将对您的本地环境进行以下更改:

  •  Install the required dependencies. 
    安装所需的依赖项。
  •  Setup the necessary scripts to run and build Storybook.
    设置运行和构建 Storybook 所需的脚本。
  • Add the default Storybook configuration.
    添加默认 Storybook 配置。
  •  Add some boilerplate stories to get you started.
    添加一些示例,让您开始学习。
  •  Set up telemetry to help us improve Storybook. Read more about it here.
    设置遥测以帮助我们改进 Storybook。点击此处了解更多信息。

Start Storybook

Storybook comes with a built-in development server featuring everything you need for project development. Depending on your system configuration, running the storybook command will start the local development server, output the address for you, and automatically open the address in a new browser tab where a welcome screen greets you.

StoryBook 附带一个内置的开发服务器,提供项目开发所需的一切。根据您的系统配置,运行 StoryBook 命令将启动本地开发服务器,为您输出地址,并在新的浏览器选项卡中自动打开地址。

pnpm run storybook

Storybook collects completely anonymous data to help us improve user experience. Participation is optional, and you may opt-out if you'd not like to share any information.

Storybook收集完全匿名的数据,帮助我们改善用户体验。参与是可选的,如果您不想分享任何信息,您可以选择退出。

Storybook welcome screen

There are some noteworthy items here:

这里有一些值得注意的项目:

  • A collection of useful links for more in-depth configuration and customization options you have at your disposal.
    一组有用的链接,可供您选择更深入的配置和自定义选项。
  • A second set of links for you to expand your Storybook knowledge and get involved with the ever-growing Storybook community.
    第二组链接可供您扩展您的故事书知识,并参与不断发展的故事书社区。
  • A few example stories to get you started.
    一些例子故事让你开始。

The Storybook CLI includes support for the industry's popular package managers (e.g., Yarnnpm, and pnpm) automatically detecting the one you are using when you initialize Storybook. However, if you want to use a specific package manager as the default, add the --package-manager flag to the installation command. For example:

Storybook CLI支持业界流行的程序包管理器(例如,Yarn、npm和pnpm),可在初始化Storybook时自动检测您正在使用的程序包。但是,如果要使用特定的包管理器作为默认值,请将--package manager标志添加到安装命令中。例如:

pnpm dlx storybook@latest init --package-manager=npm

Troubleshooting

The CLI doesn't detect my framework - CLI 无法检测到我的框架

If you're working with a custom environment set up or need set up Storybook manually, you can use the --type flag to specify the framework you need to use. Listed below are the supported frameworks and examples of how to use them:

如果您正在使用自定义环境设置或需要手动设置Storybook,则可以使用--type标志来指定需要使用的框架。下面列出了受支持的框架以及如何使用它们的示例:

FrameworkType
Angularangular
Emberember
HTMLhtml
Next.jsnextjs
Preactpreact
Qwikqwik
Reactreact
Serverserver
Solidsolid
Sveltesvelte
Vue 2vue
Vue 3vue3
Web Componentsweb-components

pnpm dlx storybook@latest init --type solid

Run Storybook with Webpack 4 - 使用Webpack 4运行Story

If you previously installed Storybook in a project that uses Webpack 4, it will no longer work. This is because Storybook now uses Webpack 5 by default. To solve this issue, we recommend you upgrade your project to Webpack 5 and then run the following command to migrate your project to the latest version of Storybook:

如果您以前在使用Webpack 4的项目中安装了Storybook,它将不再工作。这是因为Storybook现在默认使用Webpack 5。若要解决此问题,我们建议您将项目升级到Webpack 5,然后运行以下命令将项目迁移到最新版本的Storybook:

pnpm dlx storybook@latest automigrate

The installation process seems flaky and keeps failing - 安装过程似乎很不稳定,而且一直失败

If you're still running into some issues during the installation process, we encourage you to check out the following resources:

Setup StoryBook

Now that you’ve learned what stories are and how to browse them, let’s demo working on one of your components.

现在,您已经了解了什么是故事以及如何浏览它们,让我们演示一下如何使用其中一个组件。

Pick a simple component from your project, like a Button, and write a .stories.js, or a .stories.ts file to go along with it. It might look something like this:

从你的项目中选择一个简单的组件,比如Button,然后写一个.storeies.js或.storeies.ts文件来配合它。它可能看起来像这样:

import MyButton from './Button.vue';


// More on how to set up stories at: https://storybook.js.org/docs/writing-stories
export default {
  title: 'Example/Button',
  component: MyButton,
  tags: ['autodocs'],
  render: (args, { argTypes }) => ({
    props: Object.keys(argTypes),
    components: { MyButton },
    template: '<my-button @onClick="onClick" v-bind="$props" />',
  }),
  argTypes: {
    backgroundColor: { control: 'color' },
    size: {
      control: { type: 'select' },
      options: ['small', 'medium', 'large'],
    },
  },
};

// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Primary = {
  args: {
    primary: true,
    label: 'Button',
  },
};

export const Secondary = {
  args: {
    label: 'Button',
  },
};

export const Large = {
  args: {
    size: 'large',
    label: 'Button',
  },
};

export const Small = {
  args: {
    size: 'small',
    label: 'Button',
  },
};

Go to your Storybook to view the rendered component. It’s OK if it looks a bit unusual right now.

转到  Storybook  以查看渲染的组件。如果现在看起来有点不寻常也没关系。

Depending on your technology stack, you also might need to configure the Storybook environment further.

根据您的技术堆栈,您可能还需要进一步配置Storybook环境。

Render component styles 渲染组件样式

Storybook isn’t opinionated about how you generate or load CSS. It renders whatever DOM elements you provide. But sometimes, things won’t “look right” out of the box.

Storybook对如何生成或加载CSS并不固执己见。它呈现您提供的任何DOM元素。但有时,事情不会“看起来很好”。

You may have to configure your CSS tooling for Storybook’s rendering environment. Here are some setup guides for popular tools in the community.

您可能需要为Storybook的渲染环境配置CSS工具。以下是社区中流行工具的一些设置指南。

Configure Storybook for your stack - 根据你的技术栈配置 Storybook 

Storybook comes with a permissive default configuration. It attempts to customize itself to fit your setup. But it’s not foolproof.

Storybook 附带了一个允许的默认配置。它试图自定义自己以适应您的设置。但这并非万无一失。

Your project may have additional requirements before components can be rendered in isolation. This warrants customizing configuration further. There are three broad categories of configuration you might need.

在孤立地呈现组件之前,您的项目可能有其他要求。这保证了进一步自定义配置。您可能需要三大类配置。

Build configuration like Webpack and Babel - 构建如Webpack和Babel的配置

If you see errors on the CLI when you run the yarn storybook command, you likely need to make changes to Storybook’s build configuration. Here are some things to try:

如果在运行yarn storybook命令时在CLI上看到错误,则可能需要更改storybook的构建配置。以下是一些尝试:

  • Presets bundle common configurations for various technologies into Storybook. In particular, presets exist for Create React App and Ant Design.

    预设将各种技术的常见配置捆绑到Storybook中。特别是,Create React App和Ant Design都有预设。

  • Specify a custom Babel configuration for Storybook. Storybook automatically tries to use your project’s config if it can.

    为 Storybook 指定自定义Babel配置。Storybook 会自动尝试使用项目的配置(如果可以的话)。

  • Adjust the Webpack configuration that Storybook uses. Try patching in your own configuration if needed.
  • 调整 Storybook 使用的Webpack配置。如果需要,请尝试在您自己的配置中进行修补。

Runtime configuration 运行时配置

If Storybook builds but you see an error immediately when connecting to it in the browser, in that case, chances are one of your input files is not compiling/transpiling correctly to be interpreted by the browser. Storybook supports evergreen browsers, but you may need to check the Babel and Webpack settings (see above) to ensure your component code works correctly.

如果生成了Storybook,但在浏览器中连接到它时立即看到错误,在这种情况下,很可能您的一个输入文件没有正确编译/传输以供浏览器解释。Storybook支持常用浏览器,但您可能需要检查Babel和Webpack设置(见上文),以确保您的组件代码正常工作。

Component context 组件上下文

If a particular story has a problem rendering, often it means your component expects a specific environment is available to the component.

如果某个特定的故事在渲染时出现问题,通常意味着您的组件希望该组件可以使用特定的环境。

A common frontend pattern is for components to assume that they render in a specific “context” with parent components higher up the rendering hierarchy (for instance, theme providers).

一种常见的前端模式是组件假设它们在特定的“上下文”中进行渲染,父组件位于渲染层次结构的更高位置(例如,主题提供程序)。

Use decorators to “wrap” every story in the necessary context providers. The .storybook/preview.js file allows you to customize how components render in Canvas, the preview iframe. See how you can wrap every component rendered in Storybook with Styled Components ThemeProviderVue's Fontawesome, or with an Angular theme provider component in the example below.

使用decorator将每个故事“包装”在必要的上下文提供程序中。.storybook\/preview.js文件允许您自定义组件在Canvas(预览iframe)中的渲染方式。在下面的示例中,查看如何使用Styled Components ThemeProvider、Vue的Font真棒或Angular主题提供程序组件包装Storybook中渲染的每个组件。

import Vue from 'vue';

import Vuex from 'vuex';
import { library } from '@fortawesome/fontawesome-svg-core';
import { faPlusSquare as fasPlusSquare } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';

// Storybook Vue app being extended and registering the library
Vue.use(Vuex);
library.add(fasPlusSquare);

// Storybook Vue app being extended and registering the component
Vue.component('font-awesome-icon', FontAwesomeIcon);


// Storybook Vue app being extended and registering the mixin
Vue.mixin({
  // Your mixin code
});

export default {
  decorators: [
    (story) => ({
      components: { story },
      template: '<div style="margin: 3em;"><story /></div>',
    }),
  ],
};

Load assets and resources 加载静态资源

If you want to link to static files in your project or stories (e.g., /fonts/XYZ.woff), use the -s path/to/folder flag to specify a static folder to serve from when you start up Storybook. To do so, edit the storybook and build-storybook scripts in package.json.

如果要链接到项目或故事中的静态文件(例如,/fonts/XXYZ.woff),请使用 -s path/to/folder 标志指定启动 Storybook 时要使用的静态文件夹。为此,请编辑 StoryBook 并在 package.json 中执行构建脚本 build-storybook。

We recommend serving external resources and assets requested in your components statically with Storybook. It ensures that assets are always available to your stories.

我们建议使用Storybook静态地提供组件中请求的外部资源和资产。它确保资产始终可用于您的故事。

;