7.1.0 • Published 2 months ago

react-docgen v7.1.0

Weekly downloads
2,095,118
License
MIT
Repository
github
Last release
2 months ago

react-docgen Build Status

react-docgen is a CLI and toolbox to help extracting information from React components, and generate documentation from it.

It uses recast and babylon to parse the source into an AST and provides methods to process this AST to extract the desired information. The output / return value is a JSON blob / JavaScript object.

It provides a default implementation for React components defined via React.createClass, ES2015 class definitions or functions (stateless components). These component definitions must follow certain guidelines in order to be analyzable (see below for more info).

Install

Install the module directly from npm:

npm install -g react-docgen

CLI

Installing the module adds a react-docgen executable which allows you to convert a single file, multiple files or an input stream. We are trying to make the executable as versatile as possible so that it can be integrated into many workflows.

Usage: react-docgen [path]... [options]

path     A component file or directory. If no path is provided it reads from stdin.

Options:
   -o FILE, --out FILE   store extracted information in FILE
   --pretty              pretty print JSON
   -x, --extension       File extensions to consider. Repeat to define multiple extensions. Default:  [js,jsx]
   -e, --exclude         Filename pattern to exclude. Default:  []
   -i, --ignore          Folders to ignore. Default:  [node_modules,__tests__,__mocks__]
   --resolver RESOLVER   Resolver name (findAllComponentDefinitions, findExportedComponentDefinition) or
      path to a module that exports a resolver.  [findExportedComponentDefinition]

Extract meta information from React components.
If a directory is passed, it is recursively traversed.

By default, react-docgen will look for the exported component created through React.createClass, a class definition or a function (stateless component) in each file. You can change that behavior with the --resolver option, which either expects the name of a built-in resolver or a path to JavaScript module exporting a resolver function. Have a look below for more information about resolvers.

Have a look at example/ for an example of how to use the result to generate a markdown version of the documentation.

API

The tool can be used programmatically to extract component information and customize the extraction process:

var reactDocs = require('react-docgen');
var componentInfo = reactDocs.parse(src);

As with the CLI, this will look for the exported component created through React.createClass or a class definition in the provided source. The whole process of analyzing the source code is separated into two parts:

  • Locating/finding the nodes in the AST which define the component
  • Extracting information from those nodes

parse accepts more arguments with which this behavior can be customized.

parse(source [, resolver [, handlers]])

ParameterTypeDescription
sourcestringThe source text
resolverfunctionA function of the form (ast: ASTNode, recast: Object) => (NodePath|Array<NodePath>). Given an AST and a reference to recast, it returns an (array of) NodePath which represents the component definition.
handlersArray\<function>An array of functions of the form (documentation: Documentation, definition: NodePath) => void. Each function is called with a Documentation object and a reference to the component definition as returned by resolver. Handlers extract relevant information from the definition and augment documentation.

resolver

The resolver's task is to extract those parts from the source code which the handlers can analyze. For example, the findExportedComponentDefinition resolver inspects the AST to find

var Component = React.createClass(<def>);
module.exports = Component;

// or

class Component extends React.Component {
  // ...
}
module.exports = Component;

and returns the ObjectExpression to which <def> resolves to, or the class declaration itself.

findAllComponentDefinitions works similarly, but finds all React.createClass calls and class definitions, not only the one that is exported.

This makes it easy, together with the utility methods created to analyze the AST, to introduce new or custom resolver methods. For example, a resolver could look for plain ObjectExpressions with a render method.

handlers

Handlers do the actual work and extract the desired information from the result the resolver returned. Like the resolver, they try to delegate as much work as possible to the reusable utility functions.

For example, while the propTypesHandler expects the prop types definition to be an ObjectExpression and be available as propTypes in the component definition, most of the work is actually performed by the getPropType utility function.

Guidelines for default resolvers and handlers

  • Modules have to export a single component, and only that component is analyzed.
  • When using React.createClass, the component definition (the value passed to it) must resolve to an object literal.
  • When using classes, the class must either extend React.Component or define a render() method.
  • propTypes must be an object literal or resolve to an object literal in the same file.
  • The return statement in getDefaultProps must contain an object literal.

PropTypes

Example

For the following component

import React, { Component } from 'react';
import PropTypes from 'prop-types';

/**
 * General component description.
 */
class MyComponent extends Component {
  render: function() {
    // ...
  }
}

MyComponent.propTypes = {
  /**
   * Description of prop "foo".
   */
  foo: PropTypes.number,
  /**
   * Description of prop "bar" (a custom validation function).
   */
  bar: function(props, propName, componentName) {
    // ...
  },
  baz: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string
  ]),
};

MyComponent.defaultProps = {
  foo: 42,
  bar: 21
};

export default Component;

we are getting this output:

{
  "props": {
    "foo": {
      "type": {
        "name": "number"
      },
      "required": false,
      "description": "Description of prop \"foo\".",
      "defaultValue": {
        "value": "42",
        "computed": false
      }
    },
    "bar": {
      "type": {
        "name": "custom"
      },
      "required": false,
      "description": "Description of prop \"bar\" (a custom validation function).",
      "defaultValue": {
        "value": "21",
        "computed": false
      }
    },
    "baz": {
      "type": {
        "name": "union",
        "value": [
          {
            "name": "number"
          },
          {
            "name": "string"
          }
        ]
      },
      "required": false,
      "description": ""
    }
  },
  "description": "General component description."
}

Flow Type support

If you are using flow then react-docgen can also extract the flow type annotations. As flow has a way more advanced and fine granular type system, the returned types from react-docgen are different in comparison when using React.PropTypes.

Note: react-docgen will not be able to grab the type definition if the type is imported or declared in a different file.

Example

For the following component

import React, { Component } from 'react';

type Props = {
  /** Description of prop "foo". */
  primitive: number,
  /** Description of prop "bar". */
  literalsAndUnion: 'string' | 'otherstring' | number,
  arr: Array<any>,
  func?: (value: string) => void,
  noParameterName?: string => void,
  obj?: { subvalue: ?boolean },
};

/**
 * General component description.
 */
export default class MyComponent extends Component<void, Props, void> {

  props: Props;

  render(): ?ReactElement {
    // ...
  }
}

we are getting this output:

{
  "description":"General component description.",
  "props":{
    "primitive":{
      "flowType":{ "name":"number" },
      "required":true,
      "description":"Description of prop \"foo\"."
    },
    "literalsAndUnion":{
      "flowType":{
        "name":"union",
        "raw":"'string' | 'otherstring' | number",
        "elements":[
          { "name":"literal", "value":"'string'" },
          { "name":"literal", "value":"'otherstring'" },
          { "name":"number" }
        ]
      },
      "required":true,
      "description":"Description of prop \"bar\"."
    },
    "arr":{
      "flowType":{
        "name":"Array",
        "elements":[
          { "name":"any" }
        ],
        "raw":"Array<any>"
      },
      "required":true
    },
    "func":{
      "flowType":{
        "name":"signature",
        "type":"function",
        "raw":"(value: string) => void",
        "signature":{
          "arguments":[
            { "name":"value", "type":{ "name":"string" } }
          ],
          "return":{ "name":"void" }
        }
      },
      "required":false
    },
    "noParameterName":{
      "flowType":{
        "name":"signature",
        "type":"function",
        "raw":"string => void",
        "signature":{
          "arguments":[
            { "name":"", "type":{ "name":"string" } }
          ],
          "return":{ "name":"void" }
        }
      },
      "required":false
    },
    "obj":{
      "flowType":{
        "name":"signature",
        "type":"object",
        "raw":"{ subvalue: ?boolean }",
        "signature":{
          "properties":[
            {
              "key":"subvalue",
              "value":{
                "name":"boolean",
                "nullable":true,
                "required":true
              }
            }
          ]
        }
      },
      "required":false
    }
  }
}

Types

Here is a list of all the available types and its result structure.

NameExamplesResult
Simplelet x: string;let x: number;let x: boolean;let x: any;let x: void;let x: Object;let x: String;let x: MyClass;{ "name": "<type>" }
Literalslet x: 'foo';let x: 1;let x: true;{ "name": "literal", "value": "<rawvalue>" }
Typed Classeslet x: Array<foo>;let x: Class<foo>;let x: MyClass<bar>;{ "name": "<type>", "elements": [{ <element-type> }, ...] }
Object Signaturelet x: { foo: string, bar?: mixed };let x: { [key: string]: string, foo: number };{ "name": "signature", "type": "object", "raw": "<raw-signature>", "signature": { "properties": [{ "key": "<property-name>"|{ <property-key-type> }, "value": { <property-type>, "required": <true/false> } }, ...] } }
Function Signaturelet x: (x: string) => void;{ "name": "signature", "type": "function", "raw": "<raw-signature>", "signature": { "arguments": [{ "name": "<argument-name>", "type": { <argument-type> } }, ...], "return": { <return-type> } } }
Callable-Object/Function-Object Signaturelet x: { (x: string): void, prop: string };{ "name": "signature", "type": "object", "raw": "<raw-signature>", "signature": { "properties": [{ "key": "<property-name>"|{ <property-key-type> }, "value": { <property-type>, "required": <true/false> } }, ...], "constructor": { <function-signature> } } }
Tuplelet x: [foo, "value", number];{ "name": "tuple", "raw": "<raw-signature>", "elements": [{ <element-type> }, ...] }
Unionlet x: number | string;{ "name": "union", "raw": "<raw-signature>", "elements": [{ <element-type> }, ...] }
Intersectlet x: number & string;{ "name": "intersect", "raw": "<raw-signature>", "elements": [{ <element-type> }, ...] }
Nullable modifierlet x: ?number;{ "name": "number", "nullable": true }

Result data structure

The structure of the JSON blob / JavaScript object is as follows:

{
  ["description": string,]
  ["props": {
    "<propName>": {
      "type": {
        "name": "<typeName>",
        ["value": <typeValue>]
        ["raw": string]
      },
      "flowType": <flowType>,
      "required": boolean,
      "description": string,
      ["defaultValue": {
        "value": string,
        "computed": boolean
      }]
    },
    ...
  },]
  ["composes": <componentNames>]
}

([...] means the property may not exist if such information was not found in the component definition)

  • <propName>: For each prop that was found, there will be an entry in props under the same name.
  • <typeName>: The name of the type, which is usually corresponds to the function name in React.PropTypes. However, for types define with oneOf, we use "enum" and for oneOfType we use "union". If a custom function is provided or the type cannot be resolved to anything of React.PropTypes, we use "custom".
  • <typeValue>: Some types accept parameters which define the type in more detail (such as arrayOf, instanceOf, oneOf, etc). Those are stored in <typeValue>. The data type of <typeValue> depends on the type definition.
  • <flowType>: If using flow type this property contains the parsed flow type as can be seen in the table above.
babel-plugin-react-docgenbit-bin@kevincastejon/react-doc-generator@rock-kit/generate-examples@rock-kit/ui-component-examples@rock-kit/ui-docs-pluginfrontend-applicationbetter-docs-kida@pomona/pomona3-uisamurai-cli@open-tech-world/babel-plugin-rc-props@texttree/demo-bsa-reference-rclfdt-react-styleguidist@temporg/generate-examples@temporg/website-plugin@react-material-design/react-material-design@enaviga/core-components@enaviga/generic-components@datanac/datanac-api-toolkit@infinitebrahmanuniverse/nolb-react-do@framerjs/component-importer@saaspe/components@everything-registry/sub-chunk-2551@akinon/ui-docs@wacoco/ytaro-vformwinwintest123wilster-docwhale-component-docgenxiaoli-vikingsabativi-uc-example-react-eushainareusable-component-2reactlib-srigolreact-vis-docsremark-react-docgenrecodo-genredocgenredocifyredocsstalactitestorybook-addon-ondevice-autodocsstorybook21storybook-framework-redwoodjs-vitestorybook-genstorybook-preset-react-rspackstorybook-react-rsbuildsequelcomponentrsg-alttesting-storybooktest-react-eu-cemtest5amirswingsetthe-script-docuxpin-merge-tsvaadin-react@digitalfactory/design@wework/monarchanci-reactmkcp-solarpunkmobify-amp-sdkminimark-loaderminimark-plugin-propsdocmemphis-uixmodal17library-utilslimedloch-nessgross-docsgo1d-deploy-testjest-auto-snapshotsjs-to-markdownjsdoc-plugin-reactjsdocs-tssfcjgripistarfruitinsilico-tasksintelli-infrainspectrliutestatomiclotta-ui-kitmad-lib-testmozart-uigrunt-react-docgenhtmldocshumptygulp-react-docgengulp-react-docsgulp-react-docs--templateskida-docsjzm-toollazyspecladonanokit-containermakyomd-react-docgenluklak-docs-templateparvan_componentsparvan_reactjs_componentsorsa
7.1.0

2 months ago

7.0.3

12 months ago

7.0.2

12 months ago

7.0.0

1 year ago

7.0.1

1 year ago

6.0.1

2 years ago

6.0.0

2 years ago

6.0.3

1 year ago

6.0.2

1 year ago

6.0.4

1 year ago

6.0.0-rc.9

2 years ago

6.0.0-beta.5

2 years ago

6.0.0-beta.6

2 years ago

6.0.0-rc.8

2 years ago

6.0.0-rc.7

2 years ago

6.0.0-alpha.4

2 years ago

6.0.0-alpha.3

3 years ago

5.4.3

2 years ago

5.4.2

3 years ago

5.4.1

3 years ago

6.0.0-alpha.1

3 years ago

6.0.0-alpha.2

3 years ago

6.0.0-alpha.0

4 years ago

5.4.0

4 years ago

5.3.1

4 years ago

5.4.0-alpha.0

4 years ago

5.3.0

5 years ago

5.2.1

5 years ago

5.2.0

5 years ago

5.1.0

5 years ago

5.0.0

5 years ago

5.0.0-beta.1

6 years ago

4.1.1

6 years ago

4.1.0

6 years ago

4.0.1

6 years ago

4.0.0

6 years ago

3.0.0

6 years ago

3.0.0-rc.2

6 years ago

3.0.0-rc.1

6 years ago

3.0.0-rc.0

6 years ago

2.21.0

6 years ago

3.0.0-beta12

7 years ago

3.0.0-beta11

7 years ago

2.20.1

7 years ago

3.0.0-beta10

7 years ago

3.0.0-beta9

7 years ago

2.20.0

7 years ago

3.0.0-beta8

7 years ago

2.19.0

7 years ago

3.0.0-beta7

7 years ago

2.18.0

7 years ago

3.0.0-beta6

7 years ago

2.17.0

7 years ago

3.0.0-beta5

8 years ago

2.16.0

8 years ago

3.0.0-beta4

8 years ago

2.15.0

8 years ago

2.14.1

8 years ago

3.0.0-beta3

8 years ago

2.14.0

8 years ago

3.0.0-beta2

8 years ago

3.0.0-beta1

8 years ago

2.13.0

8 years ago

2.12.1

8 years ago

2.12.0

8 years ago

2.11.0

8 years ago

2.10.0

8 years ago

2.9.1

9 years ago

2.9.0

9 years ago

2.8.2

9 years ago

2.8.1

9 years ago

2.8.0

9 years ago

2.7.0

9 years ago

2.6.3

9 years ago

2.6.2

9 years ago

2.6.1

9 years ago

2.6.0

9 years ago

2.5.0

9 years ago

2.4.0

9 years ago

2.3.1

9 years ago

2.3.0

9 years ago

2.2.0

9 years ago

2.1.2

9 years ago

2.1.1

9 years ago

2.1.0

9 years ago

2.0.1

9 years ago

2.0.0

9 years ago

1.3.0

10 years ago

1.2.0

10 years ago

1.1.0

10 years ago

1.0.2

10 years ago

1.0.1

10 years ago

1.0.0

10 years ago