react-docgen

repository·main·Indexed 26 days ago

https://github.com/reactjs/react-docgen

A tool for extracting structured metadata from React components to facilitate automated documentation generation. It includes a core library for parsing components and the @react-docgen/cli for command-line extraction. The tool supports custom handlers, importers, and resolvers to control how component documentation is identified and parsed, outputting metadata as JSON objects mapping file paths to documentation arrays.

Tokens
20.9K
Snippets
71
Records
128
Agent score
86%

What's inside react-docgen

  1. Overview of react-docgen

    main

    react-docgen is a highly customizable library designed to extract information from React components and return it in a structured, machine-readable JSON format. This format can be used to automatically generate documentation.

    Key features:

    • Uses Babel to parse source code into an Abstract Syntax Tree (AST).
    • Provides methods to process the AST to extract component metadata.
    • Supports components defined via React.createClass, ES2015 class definitions, or functional (stateless) components.

    Note: react-docgen is a low-level extraction tool. If you require a full-fledged documentation style guide with a user interface, look for higher-level tools that consume react-docgen.

  2. Understand the react-docgen execution pipeline

    main

    The react-docgen processing pipeline follows four distinct steps to transform source code into documentation:

    1. Parsing: Source code is parsed using Babel.
    2. FileState Construction: A FileState object is built around the resulting Abstract Syntax Tree (AST).
    3. Resolving: A resolver identifies React component definitions within the file.
    4. Handling: Handlers process each component definition to extract specific metadata (like prop types or default props), which is then compiled into the final documentation.
  3. Understand PropTypes extraction in react-docgen

    main

    When the propTypeHandler is active, react-docgen extracts React PropTypes declarations and writes them to the type field of a prop, context, or child context descriptor.

    Extracted types include:

    • Simple types: Standard PropTypes like string, bool, number, etc.
    • Complex types: PropTypes with nested values such as oneOf() (mapped to enum), oneOfType() (mapped to union), and shape() or exact() (which produce nested descriptors in the value field).
    • Custom types: If a PropTypes expression cannot be recognized as a built-in PropType, it is recorded as a custom type, and the original printed expression is stored in the raw field.
  4. Parse component source code with parse()

    main

    Use the parse function from react-docgen to extract documentation from a string containing component source code. You can provide an options object containing a filename to help the parser identify the context.

    The output is an array of documentation objects containing component descriptions, methods, and props.

    import { parse } from 'react-docgen';
    
    const code = `
    /** My first component */
    export default ({ name }: { name: string }) => <div>{name}</div>;
    `;
    
    const documentation = parse(code, { filename: 'index.tsx' });
    
    console.log(documentation);
  5. Use componentMethodsHandler to document imperative methods

    main

    The componentMethodsHandler is used to find and document imperative methods in React components. It extracts the method name, arguments, and return types. It detects methods in the following scenarios:

    • Methods in Class components that are not React lifecycle methods or the constructor.
    • Methods assigned to static properties on Class or Function components.
    • Methods defined within the useImperativeHandle() hook in Function components.
  6. Use propTypeHandler to extract prop types

    main

    The propTypeHandler is a handler in react-docgen that attempts to find and extract prop types from React components. It identifies prop types by looking for:

    • A static property named propTypes on Class components.
    • An assignment to a property named propTypes on either Function or Class components.

    Requirement: The prop types used in your component must be imported from either the react package or the prop-types NPM package for the handler to recognize them.

    import PropTypes from 'prop-types';
    
    class MyComponent extends React.Component {
      static propTypes = {
        foo: PropTypes.string,
        bar: PropTypes.number.isRequired,
      };
      render() {
        return <div />;
      }
    }
  7. Extract TypeScript type information using react-docgen

    main

    When using the codeTypeHandler, TypeScript prop information is extracted and written to the tsType field in the resulting descriptor. To ensure the default parser enables TypeScript syntax, you must set the filename to a TypeScript extension (e.g., .ts or .tsx) when calling the parse() method.

    interface PropDescriptor {
      tsType?: TypeDescriptor<TSFunctionSignatureType>;
      required?: boolean;
      description?: string;
      defaultValue?: DefaultValueDescriptor;
    }
  8. Request to add your company or open-source tool to the Users list

    main

    If you want to include your company or an open-source tool in the react-docgen users list, you must submit a pull request to the project. You need to prepare an SVG logo for your entity and update the users.json file located in the website components directory.

    https://github.com/reactjs/react-docgen/edit/main/packages/website/src/components/users/users.json
  9. Use custom handlers with the parse() API

    main

    To use custom handlers when calling parse(), pass them in the handlers option. Note that providing a handlers array prevents the default handlers from being added automatically. If you want to extend the default behavior instead of replacing it, you must manually include defaultHandlers in your array.

    import { defaultHandlers, parse } from 'react-docgen';
    import myHandler from './myHandler.js';
    
    const docs = parse(code, {
      filename: 'Button.tsx',
      handlers: [...defaultHandlers, myHandler],
    });