I wanted to make a component visualization for a long time. I wanted to make one similar to ANTD at the beginning, and then I ran into a series of problems

The purpose of component visualization:

  1. The history component is aware and can synchronize information
  2. Ability to change the development process, ability to advance the visual acceptance of components
  3. Facilitate the unification of visual standards in the later period

Q1: How to build a component library similar to ANTD?

The investigation revealed that ANTD used the ali Bisheng package


Q2: What is bisheng’s problem?

The goal is to turn Markdown into a static site, which is how ANTD was created


Q3: Problems with Bisheng?

  1. No maintenance for a long time, document updates are lagging
  2. And the document is more difficult to read, more trouble to get started

Q4: What other solutions are on the market besides Bisheng?

This is the storybook we want to talk about this time. Currently, there are 3.7W stars, and the ecology is good, and there are many plug-ins


Q5: How to get started with storybook?

Step1: install dependencies

npm init -y
npm install @storybook/react --save-dev
npm install react react-dom --save
npm install babel-loader @babel/core --save-dev 
Copy the code

Step2: Add the script script

Add it in package.json

{
 "scripts": {
   "storybook": "start-storybook"}}Copy the code

Step3: add the config file

Create the.storybook/config.js file

import { configure } from '@storybook/react';

function loadStories() {
  require('.. /stories/index.js');
  // Multiple stores can be added
  // You can require as many stories as you need.
}

configure(loadStories, module);
Copy the code

Step4: Start writing a story

Create.. / stories/index. Js file

import React from 'react';
import { storiesOf } from '@storybook/react';
import { Button } from '@storybook/react/demo';

storiesOf('Button'.module)
  .add('with text', () = > (<Button>Hello Button</Button>
  ))
  .add('with emoji', () = > (<Button><span role="img" aria-label="so cool">😀 😎 👍 💯</span></Button>
  )); 
Copy the code

Step5: run

npm run storybook
Copy the code

The effect

  • Ok, there you go. You can now see the code you wrote

Bottom line: Storybook is configured to be relatively easy to run


Q6: How to design the directory structure?

There are three official options, and I chose the one I think is more clear

  1. Button.js is the component code
  2. Button.stories.js is the story code

According to the above design, it should be able to meet our needs


Q7: How to load on demand?

Simple configuration is not enough, if not done at the beginning, with the expansion of the business will bring a lot of problems, such as on-demand loading function is better designed from the beginning

Modified. The storybook/config. Js

import { configure } from '@storybook/react';

const req = require.context('.. /src/components'.true, /\.stories\.js$/);

function loadStories() {
  req.keys().forEach(filename= > req(filename));
}

configure(loadStories, module);
Copy the code

Q8: What is the Storybook plug-in?

  1. We have a component library up front, but we’re still a long way from viewing apis, testing, styling, and so on
  2. These additional functions need to be addressed by adding dependencies
  3. The concept of plug-ins in storybook is calledaddons

Q9: What are Addons?

  1. Addons means to add
  2. In storybook it is used to indicate added functionality

Say the most important thing three times:

In.storybook, add an addons.js file ** in.storybook, add an addons.js file ** in.storybook, Addons. js file is used to maintain the plug-in configuration file




Q10: How do you experience the first Addons?

The Addons directory on the official website is a list of recommended plug-ins


Q11: What is Addons-Knobs?


Step1: install dependencies

npm i @storybook/addon-knobs -D 
Copy the code

Step2: add configuration items

Go to.storybook/addons.js and add a sentence to it

import '@storybook/addon-knobs/register';
Copy the code

Step3: Modify the existing stories

Add the sample code according to the Github address

import React from 'react';
import { storiesOf } from '@storybook/react';
import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';

const stories = storiesOf('Storybook Knobs'.module);

// Add the `withKnobs` decorator to add knobs support to your stories.
// You can also configure `withKnobs` as a global decorator.
stories.addDecorator(withKnobs);

// Knobs for React props
stories.add('button', () = > (<button disabled={boolean('Not available ',false)} >{text(' copy ', 'knobs')}</button>
));

// Knobs as dynamic variables.
stories.add('as dynamic variables', () = > {const name = text('Name'.'Arunoda Susiripala');
  const age = number('Age'.89);

  const content = `I am ${name} and I'm ${age} years old.`;
  return (<div>{content}</div>);
});
Copy the code

Here are a few things to do:

  1. A decorator was added to stories
  2. Wrapping properties around a button, such as text(), Boolean (), and so on, is equivalent to binding properties

Look directly at the effect

Step4: Bidirectional binding effect





Step5: calculate the properties

In the example above, the second case contains the computed variable

// Knobs as dynamic variables.
stories.add('as dynamic variables', () = > {const name = text('Name'.'Arunoda Susiripala');
  const age = number('Age'.89);

  const content = `I am ${name} and I'm ${age} years old.`;
  return (<div>{content}</div>);
});
Copy the code






  1. This computed property, much like the computed property in VUE, changes the interaction as the data changes
  2. It can also quickly validate multiple states
  3. You can also quickly verify the boundary case

Q12: What are Addons-Actions


Step1: install dependencies

npm i -D @storybook/addon-actions
Copy the code

Step2: Modify.storybook/addons.js

import '@storybook/addon-actions/register';
Copy the code

Step3: bind a single event

import { storiesOf } from '@storybook/react';
import { action, configureActions } from '@storybook/addon-actions';

import Button from './button';

storiesOf('Button'.module).add('default view', () = > (<Button onClick={action('button-click')} >Hello World!</Button>
));
Copy the code

Step4: Bind multiple events

import { storiesOf } from '@storybook/react';
import { actions } from '@storybook/addon-actions';

import Button from './button';

// This will lead to { onClick: action('onClick'), ... }
const eventsFromNames = actions('onClick'.'onMouseOver');

// This will lead to { onClick: action('clicked'), ... }
const eventsFromObject = actions({ onClick: 'clicked'.onMouseOver: 'hovered' });

storiesOf('Button'.module)
  .add('default view', () = ><Button {. eventsFromNames} >Hello World!</Button>)
  .add('default view, different actions', () = > (<Button {. eventsFromObject} >Hello World!</Button>
  ));
Copy the code

Q13: What is Addons-Storysouce



Step1: install dependencies

npm i  @storybook/addon-storysource --dev
Copy the code

Step2: Create webpack.config.js

module.exports = function({ config }) {
  config.module.rules.push({
    test: /\.stories\.jsx? $/, loaders: [require.resolve('@storybook/addon-storysource/loader')],
    enforce: 'pre'});return config;
};
Copy the code

This differs from the previous two plugins in that it requires adding a loader to the Webpack, exposing the Storybook webpack itself, and adding plugins to it

Step3: Check the source code effect


Q14: What is addon-info?


Step1: install dependencies

npm i -D @storybook/addon-info
Copy the code

Step2: add plug-ins

Addon-info is in decorator mode and can be added globally or locally

  1. Global decoration is added globally in config
addDecorator(withInfo); // Globally in your .storybook/config.js.
Copy the code
  1. Locally decorated flowers are added in Stories
storiesOf('Component'.module)
  .addDecorator(withInfo) // At your stories directly..add(...) ;Copy the code

Step3: Add propTypes to the component code

import React from 'react';
import PropTypes from 'prop-types';
const Test = (props) = ><div>{props.children}</div>
Test.propTypes = {
  text: PropTypes.string.isRequired,
  onDelete: PropTypes.func,
}
export default Test
Copy the code

When addons-info is added, the Showinfo button is added





  1. Automatically changed the component name to Markdown
  2. Automatically markdown the component code
  3. PropsTypes are automatically turned into tables

However, the information in the table is still missing, including default values and descriptions

Step4: add default values and descriptions to the component code

import React from 'react';
import PropTypes from 'prop-types';
const Test = (props) = ><div>{props.children}</div>
Test.defaultProps = {
  text: 'Default value'.onDelete: (a)= >{}}; Test.propTypes = {/** where text is a comment */
  text: PropTypes.string.isRequired,
  /** where onDelete is a comment */
  onDelete: PropTypes.func,
}
export default Test
Copy the code
  1. The default value is set using defaultProps
  2. Annotations are implemented by adding annotations to properties


Q15: What is Adon-viewPort?

Viewport, you’re all familiar with that, that’s what you do with mobile

Step1: install dependencies

npm i --save-dev @storybook/addon-viewport
Copy the code

Step2: register the plug-in

Register in.storyboos/config

import '@storybook/addon-viewport/register';
Copy the code

Step3: add globally

import React from 'react';
import { configure,addDecorator,addParameters } from '@storybook/react';
// config.js
import { withInfo } from '@storybook/addon-info';
addDecorator(withInfo);
addParameters({
  viewport: { defaultViewport: 'iphone6'}});const req = require.context('.. /src/components'.true, /\.stories\.js$/);

function loadStories() {
  req.keys().forEach(filename= > req(filename));
}

configure(loadStories, module);
Copy the code

In this case, just use the addParameters method, which is very convenient



Q16: What are Addons-shots

This part is related to test cases, which can not be eaten in a short time, and will be supplemented later when there is time


Q17: What is adon-Wallpaper



Q18: What is Adon-a11y



Step1: install dependencies

npm i @storybook/addon-a11y --dev
Copy the code

Step2: register the plug-in

Modify the addons

import '@storybook/addon-a11y/register';
Copy the code

Step3: add modifiers and parameters

Add it in the config file

addDecorator(withA11y);
addParameters({
  a11y: {
    // ... axe options
    element: '#root'.// optional selector which element to inspect
    config: {}, // axe-core configurationOptions (https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#parameters-1)
    options: {} // axe-core optionsParameter (https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#options-parameter)}});Copy the code

Ok, so if you write buttons that do not conform to the specification, an error will be reported


Q19: What is Addon-console



Q20: What is Addon-links

The problem with this plug-in is that stories jump from one another and are easy to use, just by referring to the documentation


Q21: Besides these official recommended plug-ins, what else?

Here’s a list of the best plugins so far

  1. Storyshots: Snapshot tests.
  2. Specs: Interactive tests.
  3. Notes: Add a note to the story.
  4. Info: Manual for creating the CSS framework.
  5. Readme: Import markdown as a story.
  6. Actions: Event objects that display events.
  7. Intl: Added locales panel for switching languages.
  8. State: Add State panel, display or update State, and redraw view.
  9. Function Combinations: Configure all possible Props to represent multiple components at once for comparison.
  10. Knobs: changes on the page to props redraw the view.
  11. Links: Links multiple stories through the linkTo function or linkTo component.
  12. Story-router: decorator that enables storybooks to use routing components such as react-router.
  13. Wallpapers: Switching background or background color.
  14. I18n Tools: Switch text alignment to left or right.
  15. Material-UI: Adds and toggles custom themes.
  16. Host: decorator that displays components in box mode on the page.
  17. Chapters: Shows multiple components as Chapters in the same story.
  18. Options: Adjust the appearance of the storybook page, switch to full screen, etc.
  19. Console: Outputs the browser Console Console information to the Storybook Log panel.
  20. JSX Preview: Show and copy JSX code.
  21. Versions: Adds the version number to view the version changes.
  22. Apollo: Add Apollo client to simulate GraphQL query.
  23. Screenshot: Save web page screenshots.
  24. Styles: StoryBook Preview screen adds custom Styles.
  25. Figma: Added the Figma design panel.

Q22: What are the conclusions?

  1. Best part: If storybooks are thrown directly into a project, a webPack configuration can be shared, and components can be synchronized in business and in story, in real time
  2. Problems solved:
  3. Storybook primarily addresses the presentation of historical components
  4. You can also change the acceptance process to perform component acceptance before service acceptance
  5. At the same time, it is also conducive to new students
  6. Design division:
  7. Stage 1: Integrate storybooks together to improve performance
  8. Phase 2: Extract mature components to the public level for use by other projects
  9. Phase 3: Component and story separated into two project maintenance, keeping component pure and story as documentation solution

Q23: What’s on the to-do list?

  1. Display components in Showinfo
  2. Customize table styles in MarkDown
  3. Add test case development (Addons-Shots)
  4. Add color to background

Q24: What are the references?

  1. Storybook usage guide
  2. The storybook’s official website