react-styleguidist构建公共组件文档

948 阅读3分钟

刚入手现在的项目的时候会发现一个问题,就是公共组件太多了,有些甚至是复杂的业务组件,你不知道都有哪些组件,这些组件都长什么样子,是干什么的,如何去使用它。所以觉得公共组件的文档和组件库的使用文档一样重要。

项目中公共组件的文档相比于组件库的文档需要考虑很多东西。

  • 保证组件的样式一致
  • 对于组件中的action和reducer可以使用
  • 解决带请求的业务组件的跨域问题

package.json

"styleguide:dev": "styleguidist server", // 本地起服务
"styleguide:store": "node ./src/docWrapper/injectReducer.js", // 注入公共组件需要的reducer
"styleguide:build": "npm run styleguide:store && rimraf ./docs && styleguidist build && mv ./styleguide docs" // 打包

styleguide.config.js

styleguide会默认为src/components/**/*.js的js文件生成文档,所以在为业务组件创建文档时,要修改解析的components位置,所以使用components: './src/common/**',解析common组件。

为了解析组件中的一系列语法,需要配置webpackConfig项,但是要注意需要配置额外的webpack配置文件,因为业务中的webpack配置了入口文件这些,会影响解析。在初步引入项目中现有webpack的时候,会发现文档根本无法运行,因为常见的webpack中配置了entry,output这些,其实对于组件文档来说根本不需要。只需要loader/plugins等去进行解析,所以另起了一个配置文件,只保留需要的配置。

对于一些第三方样式或者全局定义的一些样式都可以使用require进行注入

现有的项目中,业务组件相比于单纯的基础组件来说,可能里面会参杂着axios请求,公共的reducer数据,action更新等。单纯的起文档会发现没有提供store,所以这个时候需要给styleguideComponents提供一个Wrapper。

使用sections配置你的文档结构 styleguide.config.js配置项

const path = require('path');

const resolve = p => path.resolve(__dirname, p);
const ConfigFactory = require('./conf/webpack/Doc');
const configInstance = new ConfigFactory();

const CommonPath = './src/common';
const join = p => path.join(CommonPath, p);
const componentMap = component => Object.keys(component).map(key => component[key]);

const joinBase = p => join(`/base/${p}`);
const baseCommon = {
  Highlight: joinBase('Highlight/index.js'),
};

const joinBusiness = p => join(`/business/${p}`);
const businessCommon = {
  AssetName: joinBusiness('AssetName/index.js')
};

module.exports = {
  serverPort: 8078,
  require: ['xx/es/styles/compact',resolve('./src/styles/theme.scss')],
  usageMode: 'expand',
  styleguideComponents: {
    Wrapper: resolve('./src/docWrapper/index.js')
  },
  components: './src/common/**',
  sections: [
    {
      name: 'base',
      components: () => componentMap(baseCommon),
      description: '业务无关组件'
    },
    {
      name: 'business',
      components: () => componentMap(businessCommon),
      description: '业务基础组件'
    }
  ],
  webpackConfig: configInstance.config
};

组件文档编写

react-styleguidist.js.org/docs/docume… 为了识别,注释要使用 /* */的形式

/**
 * 带显示隐藏按钮的密码展示输入框
 * 基本的props和Input一致
 */
function Password({defaultValue}) {
  
}
Password.propTypes = {
  /* 默认展示的值 */
  defaultValue: PropTypes.string
};

添加组件的样例,可以在当前文件下新增README.md

### 基本使用

<Password defaultValue="aaaaa"/>

store

因为项目中使用的store是根据路由权限进行配置异步注入的,所以写了一个小脚本(也就是上面的styleguide:store命令),读取本地所有的reducer进行同步注入,生成新的store文件

import React from 'react';
import {Provider} from 'react-redux';

import {store} from './stores.js';

export default function Providers({children}) {
  return <Provider store={store}>{children}</Provider>;
}

请求问题

现在为了使用开发中真实的数据,所以选择将文档通过jenkins的形式监听gitlab的代码变化,自动部署在服务器上。

当然本地可以通过配置configureServer文档)来Mock你的接口

文档效果

image.png