关于前端:React-Styleguidist-入门

此文章是由集体对该技术的了解和解读官网翻译而来,未免有不太失当的中央,望多多指教,独特学习。

react-styleguidist 会把所有组件都显示在一个页面上,蕴含 props 文档和用法示例,以及一个独立开发组件的环境。 在Styleguidist 中,能够在 Markdown 中编写示例,每个代码段都会立刻出现;

原理

Styleguidist会加载组件,应用react-docgen生成文档,可能须要更改代码能力失常工作。

React-docgen会把组件作为动态文本文件读取,而后相似于查找React组件的模式去查找组件(例如类或函数申明)。React-docgen不会运行任何JavaScript代码,因而,如果组件是动静生成,或包装在高阶组件中,或拆分为多个文件,react-docgen可能无奈了解。

React-docgen反对通过React.createClass,ES6 classes 和函数组件定义的组件;
React-docgen反对Flow和TypeScript正文;

在某些状况下,能够通过导出两个组件 坑骗 Styleguidist和react-docgen:

  • 作为命名导出的根本组件
  • 作为默认导出的加强组件
import React from 'react'
import CSSModules from 'react-css-modules'
import styles from './Button.css'

// Base component will be used by react-docgen to generate documentation
export function Button({ color, size, children }) {
  /* ... */
}

// Enhanced component will be used when you write <Button /> in your example files
export default CSSModules(Button, styles)

开始

装置 Styleguidist:

// npm
npm install --save react-styleguidist

// yarn
yarn add react-styleguidist

配置package.json脚本

"scripts": {
  "styleguide": "NODE_ENV=development styleguidist server",
  "styleguide:build": "NODE_ENV=production styleguidist build",
}

运行Styleguidist

npm run styleguide  //启动styleguidist开发服务器
npm run styleguide:build  //构建生产HTML版本

组件生成文档

Styleguidist依据组件中的正文,propTypes申明和Readerme.md为组件生成文档。

解析props

默认行为:Styleguidist从propTypes中获取props并生成一个表格,并依据props的正文显示组件的阐明,依据defaultProps获取props的默认值。

import React from 'react'
import PropTypes from 'prop-types'
/**
 * General component description in JSDoc format. Markdown is    *supported*.
 */
export default class Button extends React.Component {
  static propTypes = {
    /** Description of prop "foo". */
    foo: PropTypes.number,
    /** Description of prop "baz". */
    baz: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
  }

  static defaultProps = {
    foo: 42
  }

  render() {
    /* ... */
  }
}

批改默认行为

能够应用propsParserresolver更改解析props默认行为;

propsParser: Function
此办法能够从新个从源文件如何解析props。默认是应用react-docgen进行解析。

module.exports = {
  propsParser(filePath, source, resolver, handlers) {
    return require('react-docgen').parse(source, resolver, handlers)
  }
}

resolver
此办法能够确定哪些类/组件须要解析。默认行为是在每个文件中查找所有导出的组件,能够配置它以让所有查找到的组件应用自定义解析办法。

module.exports = {
  resolver: require('react-docgen').resolver
    .findAllComponentDefinitions
}

组件的PropType和文档正文由react-docgen库解析, 能够应用updateDocs函数对其进行批改。无关解析props的更多信息,可参见react-docgen文档。

示例文件查找与编写

默认行为:Styleguidist默认在组件文件夹下查找Readme.md[ComponentName].md的文件并生成示例文件。
带有js,jsx或javascript标记的代码块将被出现为带有交互式的React组件。为了向后兼容,不带语言标签的代码块也会展现成带有交互式的React组件。

React component example:

​```js
<Button size="large">Push Me</Button>
​```

You can add a custom props to an example wrapper:

​```js { "props": { "className": "checks" } }
<Button>I’m transparent!</Button>
​```

To render an example as highlighted source code add a `static` modifier:

​```jsx static
import React from 'react';
​```

批改默认行为

能够通过getExampleFilename自定义md 文件名字,此办法通过提供的组建文件门路返回新的 md 文件门路。
例如:用 ComponentName.examples.md代替 Readme.md

module.exports = {
  getExampleFilename(componentPath) {
    return componentPath.replace(/\.jsx?$/, '.examples.md')
  }
}

关联其余示例文件

能够应用@example doclet语法将其余示例文件与组件关联。
例子:Button 组件有一个从extra.examples.md文件加载的示例

/**
 * Component is described here.
 *
 * @example ./extra.examples.md
 */
export default class Button extends React.Component {
  // ...
}

写 code

  • 导入依赖项: 通过import导入
  • 治理状态:每个示例都是一个function组件,能够应用useState Hook来解决状态。
// ```jsx inside Markdown
import React from 'react'
import Button from 'rsg-example/components/Button'
import Placeholder from 'rsg-example/components/Placeholder'
;<Button size="large">Push Me</Button>


// ```jsx inside Markdown
const [isOpen, setIsOpen] = React.useState(false)
;<div>
  <button onClick={() => setIsOpen(true)}>Open</button>
  <Modal isOpen={isOpen}>
    <h1>Hallo!</h1>
    <button onClick={() => setIsOpen(false)}>Close</button>
  </Modal>
</div>

moduleAliases
定义模块的别名,能够在示例文件中导入这些别名,以使示例代码更加理论和可复制;

const path = require('path');

module.exports = {
  moduleAliases: {
    'rsg-example': path.resolve(__dirname, 'src')
  }
}
  • Markdown语法都被反对;
  • 如果须要在文档中显示一些不想被出现为交互式的JavaScript代码,则能够将static修饰符与语言标签一起应用;
  • Styleguidist 通过 Bublé 运行ES6代码, 大多数ES6性能都反对;
  • rsg-example模块是由moduleAliases 选项定义的别名;
  • 如果须要更简单的演示,通常最好将其定义在一个独自的JavaScript文件中,而后将其导入Markdown中

公共办法

默认状况下,组件所具备的任何办法均被视为公有办法,不会被公布。应用JSDoc @public标记办法,就能够使其成为公共办法并会在文档中公布。

/**
 * @param {string} name
 * @public
 */
getName(name) {
  // ...
}

暗藏props

默认状况下,组件所有的props都是公开并可公布。在某些状况下代码存在某props, 心愿文档中不展现这个props,应用JSDoc @ignore标记props,就能够将其从文档中删除。

Button.propTypes = {
  /**
   * A prop that should not be visible in the documentation.
   * @ignore
   */
  hiddenProp: React.PropTypes.string
}

定位组件

查找组件

默认状况下,Styleguidist将应用此模式定位组件:src/components/**/*.{js,jsx,ts,tsx}
例如:

  • src/components/Button.js
  • src/components/Button/Button.js
  • src/components/Button/index.js

然而会疏忽 tests 文件:

  • __tests__ 文件夹
  • 文件名里蕴含.test.js.spec.js (相似于: .jsx, .ts , .tsx)

批改默认查找形式

styleguide.config.js文件里的配置components能够批改组件查找形式来适应不同的我的项目;

例如:如果组件门路是components/Button/Button.js,为了简化导入在components/Button/index.js中再次导出(export { default } from './Button'),【为了让components/Button代替components/Button/Button】, 这时候须要跳过 index.js。

module.exports = {
  components: 'src/components/**/[A-Z]*.js'
}

应用ignore可将某些文件从款式指南中排除

ignore:String[]

默认值:

[
  '**/__tests__/**', 
  '**/*.test.{js,jsx,ts,tsx}', 
  '**/*.spec.{js,jsx,ts,tsx}', 
  '**/*.d.ts'
]

应用getComponentPathLine更改组件导入门路

getComponentPathLine: Function
默认值: 组件文件名
返回值:返回组件门路

例如: 从components/Button中导入Button,而不是components/Button /Button.js

const path = require('path');
module.exports = {
  getComponentPathLine(componentPath) {
    const name = path.basename(componentPath, '.js')
    const dir = path.dirname(componentPath)
    return `import ${name} from '${dir}';`
  }
}

所有门路都绝对于config文件夹;

加载组件

Styleguidist加载组件并裸露在全局以供示例应用。

标识符

Styleguidist默认应用组件的displayName作为标识符。如果它不能了解displayName(displayName动静生成),它将退回到它能够了解的货色。

Sections

Sections: Array[{}]

将组件分组,或将额定的Markdown文档增加到款式指南中。

Sections数组的每一项有:

  • name — Sections 题目;
  • content — 蕴含概述内容的Markdown文件的地位;
  • components — 能够是glob模式字符串,组件门路数组,glob模式字符串数组,返回一个组件数组的函数或返回glob模式字符串的函数。规定与根选项components雷同;
  • sections — 嵌套的Sections数组(能够再嵌套);
  • description — section形容;
  • sectionDepth — 单个页面的大节数,仅在pagePerSection中可用;
  • exampleMode — 代码示例的初始状态,应用 exampleMode.
  • usageMode — props和办法的初始状态, 应用 usageMode.
  • ignore — 须要疏忽的文件,值能够是字符串或数组;
  • href – navigate的URL(不是导航到Sections 内容的URL);
  • external – 如果设置,会关上一个新页面;
  • expand – 在惯例设置中将tocMode设置为collapse折叠时,确认是否应该被开展;

上述所有字段都是可选的;

// styleguide.config.js

module.exports = {
  sections: [
    {
      name: 'Introduction',
      content: 'docs/introduction.md'
    },
    {
      name: 'Documentation',
      sections: [
        {
          name: 'Installation',
          content: 'docs/installation.md',
          description: 'The description for the installation section'
        },
        {
          name: 'Configuration',
          content: 'docs/configuration.md'
        },
        {
          name: 'Live Demo',
          external: true,
          href: 'http://example.com'
        }
      ]
    },
    {
      name: 'UI Components',
      content: 'docs/ui.md',
      components: 'lib/components/ui/*.js',
      exampleMode: 'expand', // 'hide' | 'collapse' | 'expand'
      usageMode: 'expand' // 'hide' | 'collapse' | 'expand'
    }
  ]
}

配置webpack

Styleguidist依赖webpack,应用webpack确定如何加载我的项目的文件,但我的项目也不肯定非要配置webpack。
默认状况下,Styleguidist会在我的项目的根目录中查找webpack.config.js并应用它。

自定义Webpack配置

如果webpack配置在其余地位,则须要手动加载:

module.exports = {
  webpackConfig: require('./configs/webpack.js')
}

也能够merge多个webpack配置:

module.exports = {
  webpackConfig: Object.assign({}, require('./configs/webpack.js'), {
    /* Custom config options */
  })
}
  • 配置entry, externals, output, watch, 和 stats .会被疏忽。生产上,devtool 也会被疏忽;
  • 插件 CommonsChunkPlugins, HtmlWebpackPlugin, MiniHtmlWebpackPlugin, UglifyJsPlugin, TerserPlugin, HotModuleReplacementPlugin 会被疏忽, 因为 Styleguidist 曾经引入了他们,再次引入会影响 Styleguidist;
  • 如果loaders 不起作用,请尝试蕴含和排除绝对路径;

styleguide配置

title: String

serverPort: Number
端口号

require: Array
增加用户自定义的js, CSS 或 polyfills

assetsDir: String
资源文件名

styleguideDir: String
默认值:styleguide
定义styleguidist构建命令生成的动态HTML的文件夹;

getComponentPathLine: Function
获取组件加载门路

template: Object | Function
更改应用程序的HTML。 一个能够增加favicon,meta 标签, 内嵌JavaScript或CSS的对象。

styles: Object | String | Function
自定义Styleguidist组件的款式。

theme: Object | String
配置值能够是对象或导出此类对象的文件的门路实现自定义UI字体,色彩等;
配置的文件门路是绝对配置文件或者绝对路径。

sections
设置组件分组;

styleguideComponents: Object
重写被用于渲染到浏览器的React组件;

webpackConfig
自定义webpack配置;

更多配置选项查看官网文档:configuration

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理