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:
- The history component is aware and can synchronize information
- Ability to change the development process, ability to advance the visual acceptance of components
- 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?
- No maintenance for a long time, document updates are lagging
- 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
- Button.js is the component code
- 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?
- We have a component library up front, but we’re still a long way from viewing apis, testing, styling, and so on
- These additional functions need to be addressed by adding dependencies
- The concept of plug-ins in storybook is called
addons
Q9: What are Addons?
- Addons means to add
- 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:
- A decorator was added to stories
- 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
- This computed property, much like the computed property in VUE, changes the interaction as the data changes
- It can also quickly validate multiple states
- 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
- Global decoration is added globally in config
addDecorator(withInfo); // Globally in your .storybook/config.js.
Copy the code
- 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
- Automatically changed the component name to Markdown
- Automatically markdown the component code
- 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
- The default value is set using defaultProps
- 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
- Storyshots: Snapshot tests.
- Specs: Interactive tests.
- Notes: Add a note to the story.
- Info: Manual for creating the CSS framework.
- Readme: Import markdown as a story.
- Actions: Event objects that display events.
- Intl: Added locales panel for switching languages.
- State: Add State panel, display or update State, and redraw view.
- Function Combinations: Configure all possible Props to represent multiple components at once for comparison.
- Knobs: changes on the page to props redraw the view.
- Links: Links multiple stories through the linkTo function or linkTo component.
- Story-router: decorator that enables storybooks to use routing components such as react-router.
- Wallpapers: Switching background or background color.
- I18n Tools: Switch text alignment to left or right.
- Material-UI: Adds and toggles custom themes.
- Host: decorator that displays components in box mode on the page.
- Chapters: Shows multiple components as Chapters in the same story.
- Options: Adjust the appearance of the storybook page, switch to full screen, etc.
- Console: Outputs the browser Console Console information to the Storybook Log panel.
- JSX Preview: Show and copy JSX code.
- Versions: Adds the version number to view the version changes.
- Apollo: Add Apollo client to simulate GraphQL query.
- Screenshot: Save web page screenshots.
- Styles: StoryBook Preview screen adds custom Styles.
- Figma: Added the Figma design panel.
Q22: What are the conclusions?
- 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
- Problems solved:
- Storybook primarily addresses the presentation of historical components
- You can also change the acceptance process to perform component acceptance before service acceptance
- At the same time, it is also conducive to new students
- Design division:
- Stage 1: Integrate storybooks together to improve performance
- Phase 2: Extract mature components to the public level for use by other projects
- 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?
- Display components in Showinfo
- Customize table styles in MarkDown
- Add test case development (Addons-Shots)
- Add color to background
Q24: What are the references?
- Storybook usage guide
- The storybook’s official website