Babel Plugin for React Docgen

4.2.1 · maintenance · verified Sun Apr 19

The `babel-plugin-react-docgen` package is a Babel plugin designed to embed documentation metadata, generated by `react-docgen`, directly into React component definitions during the build process. Instead of requiring a separate build step or runtime parsing, this plugin augments your React components with a `__docgenInfo` static property, making propType descriptions, component descriptions, and other metadata programmatically accessible at runtime. This capability is highly beneficial for tools such as Storybook, style guides, or developer tools that consume component metadata. The current stable version is 4.2.1. The project appears to have an infrequent release cadence, with major versions released every few years, often in response to updates in `react-docgen` or the Babel ecosystem itself. Its key differentiator is the seamless integration of docgen output directly into the component's generated code, simplifying access to documentation metadata.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the basic installation and configuration of the plugin in `babel.config.js`, along with an example React component showing how `__docgenInfo` is generated.

npm install -D babel-plugin-react-docgen @babel/core @babel/cli

// babel.config.js
module.exports = {
  plugins: [
    "react-docgen"
  ],
  // Ensure Babel processes your React files, e.g., with @babel/preset-react
  // presets: ['@babel/preset-react', '@babel/preset-env']
};

// src/Button.jsx
import React from 'react';
import PropTypes from 'prop-types'; // Use prop-types package

/**
 * This is an example button component for demonstration purposes.
 */
export default class Button extends React.Component {
  render() {
    const { label, onClick } = this.props;
    return (
      <button onClick={onClick}>{ label }</button>
    );
  }
}

Button.propTypes = {
  /**
   * The text label for the button.
   */
  label: PropTypes.string,
  /**
   * Function called when the button is clicked.
   */
  onClick: PropTypes.func,
};

// To access the generated info after Babel compilation (e.g., in a documentation builder)
// console.log(Button.__docgenInfo);
/* Expected structure of Button.__docgenInfo:
{
  description: 'This is an example button component for demonstration purposes.',
  props: {
    label: {
      type: { name: 'string' },
      required: false,
      description: 'The text label for the button.'
    },
    onClick: {
      type: { name: 'func' },
      required: false,
      description: 'Function called when the button is clicked.'
    }
  }
}
*/

view raw JSON →