关于前端:React-Styleguidist-入门

13次阅读

共计 7435 个字符,预计需要花费 19 分钟才能阅读完成。

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

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

正文完
 0