React TypeScript Docgen Parser

2.4.0 · active · verified Sun Apr 19

This library, `react-docgen-typescript`, provides a robust parser for extracting documentation information from React components written in TypeScript. It analyzes TypeScript files to generate documentation data, similar to how `react-docgen` works for JavaScript components with `propTypes`. The current stable version is 2.4.0, with releases occurring semi-frequently, indicating active maintenance and feature development based on recent changelogs. Its primary differentiator is its native support for TypeScript, allowing it to correctly interpret complex type definitions, interfaces, and generics to generate detailed prop tables, including descriptions, types, and default values. It is often used in conjunction with tools like React Styleguidist to automatically generate component documentation.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to parse a TypeScript React component using `withCustomConfig` to specify a `tsconfig.json` and custom docgen options, then prints the generated documentation to the console.

import { withCustomConfig } from 'react-docgen-typescript';
import * as fs from 'fs';
import * as path from 'path';

// Define a dummy component file for demonstration
const componentCode = `
import React from 'react';

interface ButtonProps {
  /**
   * The text content of the button.
   */
  label: string;
  /**
   * Is this the principal call to action on the page?
   * @default false
   */
  primary?: boolean;
  /**
   * What background color to use
   */
  backgroundColor?: string;
  /**
   * How large should the button be?
   * @default 'medium'
   */
  size?: 'small' | 'medium' | 'large';
  /**
   * Optional click handler
   */
  onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
}

/**
 * A primary button component
 */
export const Button: React.FC<ButtonProps> = ({
  label,
  primary = false,
  backgroundColor,
  size = 'medium',
  onClick,
}) => {
  const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
  return (
    <button
      type="button"
      className={['storybook-button', `storybook-button--${size}`, mode].join(' ')}
      style={{ backgroundColor }}
      onClick={onClick}
    >
      {label}
    </button>
  );
};
`;

const tempDir = path.join(__dirname, 'temp');
if (!fs.existsSync(tempDir)) {
  fs.mkdirSync(tempDir);
}
const tempComponentPath = path.join(tempDir, 'Button.tsx');
fs.writeFileSync(tempComponentPath, componentCode);

// Create a basic tsconfig.json for the parser
const tsconfigPath = path.join(tempDir, 'tsconfig.json');
fs.writeFileSync(tsconfigPath, JSON.stringify({
  compilerOptions: {
    jsx: "react",
    module: "ESNext",
    target: "ESNext",
    esModuleInterop: true,
    strict: true,
    skipLibCheck: true,
  },
  include: [tempDir + "/**/*"]
}, null, 2));


const parser = withCustomConfig(tsconfigPath, {
  shouldExtractLiteralValuesFromEnum: true,
  propFilter: {
    skipPropsWithoutDoc: true,
  },
});

try {
  const componentDocs = parser.parse(tempComponentPath);
  console.log(JSON.stringify(componentDocs, null, 2));
} catch (error) {
  console.error("Error parsing component:", error);
} finally {
  // Clean up temporary files
  fs.unlinkSync(tempComponentPath);
  fs.unlinkSync(tsconfigPath);
  fs.rmdirSync(tempDir);
}

view raw JSON →