自动配置storybook
react 项目
npx -p @storybook/cli sb init --type react
create react app + 下面命令
If you’re using Create React App (or a fork of
react-scripts), you should use this command instead:
npx -p @storybook/cli sb init --type react_scripts
Note: 项目中必须有package.json , 否则上面的命令会报错
手动配置storybook
1- 按照依赖
npm install @storybook/react --save-dev
npm install react react-dom --save
npm install babel-loader @babel/core --save-dev
2- 配置脚本
// package.json
{
  "scripts": {
    "storybook": "start-storybook"
  }
}
3- Create the main file (告诉storybook去哪找stories)
// .storybook/main.js
module.exports = {
  stories: ['../src/**/*.stories.[tj]s'],  // 加载src目录下的所有的以stories.js/ts结尾的文件,stories文件路径
};
4- write stories
// ../src/index.stories.js
import React from 'react';
import { Button } from '@storybook/react/demo';
export default { title: 'Button' };
export const withText = () => <Button>Hello Button</Button>;
export const withEmoji = () => (
  <Button>
    <span role="img" aria-label="so cool">
      😀 😎 👍 💯
    </span>
  </Button>
);
每个story是组件的一个状态,如上例:按钮组件的两个实例
Button
├── With Text
└── With Emoji
5- 启动storybook
npm run storybook
webpack配置
Debug the default webpack config
1- 获取完整的webpack默认配置
// .storybook/main.js
module.exports = {
webpackFinal: (config) => console.dir(config, { depth: null }) || config,
};
执行命令
yarn storybook --debug-webpack
2- webpackFinal添加配置
函数
参数: 第一个参数是storybook使用的webpack配置,第二个参数是接收的来自storybook的对象, 可以告诉你这些配置来自哪里
For example, here’s a .storybook/main.js to add Sass support:
const path = require('path');
// Export a function. Accept the base config as the only param.
module.exports = {
  webpackFinal: async (config, { configType }) => {
    // `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
    // You can change the configuration based on that.
    // 'PRODUCTION' is used when building the static version of storybook.
    // Make whatever fine-grained changes you need
    config.module.rules.push({
      test: /\.scss$/,
      use: ['style-loader', 'css-loader', 'sass-loader'],
      include: path.resolve(__dirname, '../'),
    });
    // Return the altered config
    return config;
  },
};
添加插件配置
module.exports = {
  webpackFinal: (config) => {
    config.plugins.push(...);
    return config;
  },
}
Using Your Existing Config---merge two config
Example replacing the loaders from storybook with the loaders from your app’s webpack.config.js
const path = require('path');
// your app's webpack.config.js
const custom = require('../webpack.config.js');
module.exports = {
  webpackFinal: (config) => {
    return { ...config, module: { ...config.module, rules: custom.module.rules } };
  },
};
Custom Babel Config
默认情况下,Storybook加载根.babelrc文件并加载这些配置。但有时这些选择可能会导致故事书抛出错误。
在这种情况下,您可以为Storybook提供一个定制的.babelrc。为此,在Storybook config目录中创建一个名为.babelrc文件的文件(默认情况下,它是.Storybook)。
然后Storybook将只从该文件加载Babel配置。目前我们不支持package.json中的 Babel config
TypeScript Config
1- Typescript configuration presets
- 如果你使用Create React App (CRA) 并且配置了TS, 需要安装@storybook/preset-create-react-app让storybook也使用TS
- 如果你不使用CRA, 最佳选择是@storybook/preset-typescript
2- Setting up TypeScript with ts-loader
- 安包
yarn add -D typescript
yarn add -D ts-loader
yarn add -D @storybook/addon-info react-docgen-typescript-loader # optional but recommended
yarn add -D jest "@types/jest" ts-jest #testing
- 配置
// .storybook/main.js
module.exports = {
  stories: ['../src/**/*.stories.tsx'],
  webpackFinal: async config => {
    config.module.rules.push({
      test: /\.(ts|tsx)$/,
      use: [
        {
          loader: require.resolve('ts-loader'),
        },
        // Optional
        {
          loader: require.resolve('react-docgen-typescript-loader'),
        },
      ],
    });
    config.resolve.extensions.push('.ts', '.tsx');
    return config;
  },
};
- 根据stories存放目录修改 tsconfig.json
"rootDirs": ["src", "stories"],
3- Setting up TypeScript with babel-loader
- 安包
 @storybook/preset-create-react-app: create-react-app + typescript
- 配置
// .storybook/main.js
module.exports = {
  stories: ['../src/**/*.stories.tsx'],
  webpackFinal: async config => {
    config.module.rules.push({
      test: /\.(ts|tsx)$/,
      loader: require.resolve('babel-loader'),
      options: {
        presets: [['react-app', { flow: false, typescript: true }]],
      },
    });
    config.resolve.extensions.push('.ts', '.tsx');
    return config;
  },
};
3- Using TypeScript with the TSDocgen addon
storybook info addon 能自动为每个组件生成属性表文档, 但是不适用与typescript
解决方案:react docgen typescript loader预处理typescript文件,以向Info插件提供所需的内容,webpack配置如上
组件正常使用info即可
import * as React from 'react';
import TicTacToeCell from './TicTacToeCell';
export default {
  title: 'Components',
  parameters: {
    info: { inline: true },
  },
};
export const TicTacToeCell = () => (
  <TicTacToeCell value="X" position={{ x: 0, y: 0 }} />,
);
请参阅react docgen typescript loader文档,以向typescript接口写入属性说明和其他注释。
可以在.storybook/preview.js中添加其他的说明
import { addDecorator } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
addDecorator(
  withInfo({
    styles: {
      header: {
        h1: {
          marginRight: '20px',
          fontSize: '25px',
          display: 'inline',
        },
        body: {
          paddingTop: 0,
          paddingBottom: 0,
        },
        h2: {
          display: 'inline',
          color: '#999',
        },
      },
      infoBody: {
        backgroundColor: '#eee',
        padding: '0px 5px',
        lineHeight: '2',
      },
    },
    inline: true,
    source: false,
  })
);
注意:对于只导出为默认值的组件,无法生成组件docgen信息。通过使用命名导出导出组件,可以解决此问题。
4- Setting up Jest tests
This is an example jest.config.js file for jest:
module.exports = {
  transform: {
    '.(ts|tsx)': 'ts-jest',
  },
  testPathIgnorePatterns: ['/node_modules/', '/lib/'],
  testRegex: '(/test/.*|\\.(test|spec))\\.(ts|tsx|js)$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
};
6- Building your TypeScript Storybook
  "scripts": {
    "start": "react-scripts-ts start",
    "build": "npm run lint && npm run build-lib && build-storybook",
    "build-lib-watch": "tsc -w",
    "build-lib": "tsc && npm run copy-css-to-lib && npm run copy-svg-to-lib && npm run copy-png-to-lib && npm run copy-woff2-to-lib",
    "test": "react-scripts-ts test --env=jsdom",
    "test:coverage": "npm test -- --coverage",
    "eject": "react-scripts-ts eject",
    "storybook": "start-storybook -p 6006",
    "build-storybook": "build-storybook",
    "copy-css-to-lib": "cpx \"./src/**/*.css\" ./build/lib",
    "copy-woff2-to-lib": "cpx \"./src/**/*.woff2\" ./build/lib",
    "copy-svg-to-lib": "cpx \"./src/**/*.svg\" ./build/lib",
    "copy-png-to-lib": "cpx \"./src/**/*.png\" ./build/lib",
    "lint": "tslint -c tslint.json 'src/**/*.{ts,tsx}'"
  },