Convert Figma logo to code with AI

styleguidist logoreact-docgen-typescript

A simple parser for react properties defined in typescript instead of propTypes.

1,187
253
1,187
26

Top Related Projects

A CLI and library to extract information from React component files for documentation generation purposes.

83,945

Storybook is the industry standard workshop for building, documenting, and testing UI components in isolation

23,600

✍ It has never been so easy to document your things!

14,962

An API documentation generator for JavaScript.

7,644

Documentation generator for TypeScript projects.

Easy to maintain open source documentation websites.

Quick Overview

React-docgen-typescript is a parser for React components written in TypeScript. It extracts information about component props, methods, and descriptions from TypeScript files, making it easier to generate documentation for React components automatically.

Pros

  • Supports TypeScript, providing accurate type information for props and methods
  • Integrates well with other documentation tools like Styleguidist and Storybook
  • Automatically extracts component descriptions from JSDoc comments
  • Handles complex TypeScript types and interfaces

Cons

  • May struggle with some advanced TypeScript features or complex component structures
  • Documentation generation can be slower compared to JavaScript-only alternatives
  • Requires proper TypeScript setup and configuration in the project
  • Limited customization options for output format

Code Examples

  1. Basic usage:
import { parse } from 'react-docgen-typescript';

const componentInfo = parse('path/to/component.tsx');
console.log(componentInfo);
  1. Parsing multiple files:
import { parse } from 'react-docgen-typescript';

const componentInfoArray = parse(['component1.tsx', 'component2.tsx']);
componentInfoArray.forEach(info => console.log(info));
  1. Using custom parser options:
import { withCustomConfig } from 'react-docgen-typescript';

const customParser = withCustomConfig('tsconfig.json', {
  propFilter: (prop, component) => {
    if (prop.declarations !== undefined && prop.declarations.length > 0) {
      const hasPropAdditionalDescription = (prop.declarations[0] as any).comment;
      return Boolean(hasPropAdditionalDescription);
    }
    return true;
  },
});

const componentInfo = customParser.parse('path/to/component.tsx');
console.log(componentInfo);

Getting Started

To use react-docgen-typescript in your project:

  1. Install the package:
npm install --save-dev react-docgen-typescript
  1. Create a script to parse your components:
import { parse } from 'react-docgen-typescript';
import * as fs from 'fs';

const componentInfo = parse('src/components/MyComponent.tsx');
fs.writeFileSync('docs/MyComponent.json', JSON.stringify(componentInfo, null, 2));
  1. Run the script to generate documentation for your components.

Competitor Comparisons

A CLI and library to extract information from React component files for documentation generation purposes.

Pros of react-docgen

  • Broader support for React components, including class components and functional components
  • Integrated with the official React documentation tooling
  • More extensive parsing capabilities for complex component structures

Cons of react-docgen

  • Limited TypeScript support compared to react-docgen-typescript
  • May require additional configuration for TypeScript projects
  • Less detailed type information extraction for TypeScript components

Code Comparison

react-docgen:

const docgen = require('react-docgen');
const componentInfo = docgen.parse(source);
console.log(componentInfo.props);

react-docgen-typescript:

import { parse } from 'react-docgen-typescript';
const componentInfo = parse('path/to/component.tsx');
console.log(componentInfo[0].props);

Both tools aim to extract component documentation, but react-docgen-typescript is specifically designed for TypeScript projects, offering better type inference and more accurate prop descriptions for TypeScript components. react-docgen, on the other hand, provides a more comprehensive solution for JavaScript-based React projects and has better integration with the React ecosystem.

The choice between the two depends on the project's primary language (JavaScript or TypeScript) and the level of type information needed in the generated documentation. For TypeScript-heavy projects, react-docgen-typescript might be more suitable, while react-docgen remains a solid choice for JavaScript-based React applications.

83,945

Storybook is the industry standard workshop for building, documenting, and testing UI components in isolation

Pros of Storybook

  • Provides a comprehensive UI development environment with built-in tools for testing, documentation, and visual regression
  • Supports multiple frontend frameworks beyond React, including Vue, Angular, and Svelte
  • Offers a rich ecosystem of addons and integrations for enhanced functionality

Cons of Storybook

  • Steeper learning curve and more complex setup compared to react-docgen-typescript
  • Can be overkill for smaller projects or teams that only need basic component documentation

Code Comparison

react-docgen-typescript:

import { withInfo } from '@storybook/addon-info';
import { ComponentDoc } from 'react-docgen-typescript';

const docgenInfo = (ComponentDoc as any).__docgenInfo;

Storybook:

import { Meta, Story } from '@storybook/react';
import { Button } from './Button';

export default {
  title: 'Components/Button',
  component: Button,
} as Meta;

const Template: Story = (args) => <Button {...args} />;

While react-docgen-typescript focuses on generating component documentation from TypeScript code, Storybook provides a more comprehensive development environment for building and showcasing UI components. Storybook's approach involves creating stories for components, which can include documentation, interactive examples, and various states of the component.

23,600

✍ It has never been so easy to document your things!

Pros of docz

  • More user-friendly and easier to set up, with a focus on MDX-based documentation
  • Provides a live-reloading development environment out of the box
  • Offers customizable themes and plugins for enhanced flexibility

Cons of docz

  • Less focused on automatic prop type extraction compared to react-docgen-typescript
  • May require more manual documentation writing in MDX format
  • Can be overkill for smaller projects or simple component libraries

Code Comparison

react-docgen-typescript:

import { ComponentDoc } from 'react-docgen-typescript';

const docs = parse('path/to/component.tsx');
console.log(docs[0].props);

docz:

---
name: Button
route: /button
---

import { Playground, Props } from 'docz'
import { Button } from './Button'

# Button

<Props of={Button} />

<Playground>
  <Button>Click me</Button>
</Playground>

Summary

While react-docgen-typescript excels at automatic prop type extraction and integration with existing documentation tools, docz provides a more comprehensive documentation solution with a focus on developer experience and customization. The choice between the two depends on project requirements, team preferences, and the desired level of automation in documentation generation.

14,962

An API documentation generator for JavaScript.

Pros of jsdoc

  • Language-agnostic, supporting JavaScript, TypeScript, and other languages
  • Extensive documentation and community support
  • Flexible and customizable with plugins and templates

Cons of jsdoc

  • Requires manual annotation of code, which can be time-consuming
  • May not capture all TypeScript-specific features accurately
  • Output can be more verbose and less React-specific

Code Comparison

jsdoc:

/**
 * @typedef {Object} Props
 * @property {string} name - The name of the user
 * @property {number} age - The age of the user
 */

/**
 * A user component
 * @param {Props} props - The component props
 * @returns {JSX.Element} The rendered component
 */
function User({ name, age }) {
  // Component logic
}

react-docgen-typescript:

interface Props {
  /** The name of the user */
  name: string;
  /** The age of the user */
  age: number;
}

/**
 * A user component
 */
function User({ name, age }: Props) {
  // Component logic
}

react-docgen-typescript is specifically designed for React and TypeScript, offering more streamlined documentation for React components. It automatically extracts type information from TypeScript interfaces and types, reducing the need for manual annotations. However, jsdoc provides broader language support and more extensive customization options, making it suitable for a wider range of projects beyond React and TypeScript.

7,644

Documentation generator for TypeScript projects.

Pros of TypeDoc

  • Supports a wider range of TypeScript projects, not limited to React components
  • Generates comprehensive documentation with a hierarchical structure
  • Offers more customization options for output formats and themes

Cons of TypeDoc

  • May produce more verbose output, which can be overwhelming for simpler projects
  • Requires more configuration to achieve desired results
  • Less focused on component-specific documentation compared to react-docgen-typescript

Code Comparison

TypeDoc example:

/**
 * Represents a user in the system.
 * @param name The user's full name
 * @param age The user's age
 */
interface User {
  name: string;
  age: number;
}

react-docgen-typescript example:

interface Props {
  /** The user's full name */
  name: string;
  /** The user's age */
  age: number;
}

/**
 * A component that displays user information.
 */
const UserInfo: React.FC<Props> = ({ name, age }) => {
  // Component implementation
};

TypeDoc is better suited for documenting entire TypeScript projects, including interfaces, classes, and functions. It provides a more comprehensive documentation structure but may require more setup.

react-docgen-typescript is specifically designed for React components and props, offering a more streamlined approach for component-based documentation. It's easier to set up for React projects but has limited use outside of that context.

Easy to maintain open source documentation websites.

Pros of Docusaurus

  • Comprehensive static site generator designed for documentation websites
  • Supports versioning, search, and internationalization out of the box
  • Extensive plugin ecosystem and customization options

Cons of Docusaurus

  • Steeper learning curve due to its broader feature set
  • May be overkill for simple documentation needs
  • Requires more setup and configuration compared to react-docgen-typescript

Code Comparison

react-docgen-typescript:

import { parse } from 'react-docgen-typescript';

const docs = parse('path/to/component.tsx');
console.log(docs);

Docusaurus:

// docusaurus.config.js
module.exports = {
  title: 'My Site',
  tagline: 'Documentation made easy',
  url: 'https://mysite.com',
  baseUrl: '/',
  // ... more configuration options
};

While react-docgen-typescript focuses on extracting component documentation from TypeScript files, Docusaurus provides a full-fledged documentation website solution. react-docgen-typescript is more suitable for generating component documentation programmatically, while Docusaurus excels in creating comprehensive documentation websites with additional features like versioning and search.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

react-docgen-typescript

Build Status

A simple parser for React properties defined in TypeScript instead of propTypes.

It can be used with React Styleguidist.

Installation

npm install --save-dev react-docgen-typescript

Usage

To parse a file for docgen information use the parse function.

const docgen = require("react-docgen-typescript");

const options = {
  savePropValueAsString: true,
};

// Parse a file for docgen info
docgen.parse("./path/to/component", options);

If you want to customize the typescript configuration or docgen options, this package exports a variety of ways to create custom parsers.

const docgen = require("react-docgen-typescript");

// Create a parser with the default typescript config and custom docgen options
const customParser = docgen.withDefaultConfig(options);

const docs = customParser.parse("./path/to/component");

// Create a parser with the custom typescript and custom docgen options
const customCompilerOptionsParser = docgen.withCompilerOptions(
  { esModuleInterop: true },
  options
);

// Create a parser with using your typescript config
const tsConfigParser = docgen.withCustomConfig("./tsconfig.json", {
  savePropValueAsString: true,
});

React Styleguidist integration

Include following line in your styleguide.config.js:

module.exports = {
  propsParser: require("react-docgen-typescript").withDefaultConfig([
    parserOptions,
  ]).parse,
};

or if you want to use custom tsconfig file

module.exports = {
  propsParser: require("react-docgen-typescript").withCustomConfig(
    "./tsconfig.json",
    [parserOptions]
  ).parse,
};

Options

propFilter

The propFilter option allows you to omit certain props from documentation generation.

You can either provide and object with some of our pre-configured filters:

interface FilterOptions {
  skipPropsWithName?: string[] | string;
  skipPropsWithoutDoc?: boolean;
}

const options = {
  propFilter: {
    skipPropsWithName: ['as', 'id'];
    skipPropsWithoutDoc: true;
  }
}

If you do not want to print out all the HTML attributes of a component typed like the following:

const MyComponent: React.FC<React.HTMLAttributes<HTMLDivElement>> = ()...

you can provide a propFilter function and do the filtering logic yourself.

type PropFilter = (prop: PropItem, component: Component) => boolean;

const options = {
  propFilter: (prop: PropItem, component: Component) => {
    if (prop.declarations !== undefined && prop.declarations.length > 0) {
      const hasPropAdditionalDescription = prop.declarations.find((declaration) => {
        return !declaration.fileName.includes("node_modules");
      });

      return Boolean(hasPropAdditionalDescription);
    }

    return true;
  },
};

Note: children without a doc comment will not be documented.

componentNameResolver

(exp: ts.Symbol, source: ts.SourceFile) => string | undefined | null | false;

If a string is returned, then the component will use that name. Else it will fallback to the default logic of parser.

shouldExtractLiteralValuesFromEnum: boolean

If set to true, string enums and unions will be converted to docgen enum format. Useful if you use Storybook and want to generate knobs automatically using addon-smart-knobs.

shouldExtractValuesFromUnion: boolean

If set to true, every unions will be converted to docgen enum format.

shouldSortUnions: boolean

When used in combination with shouldExtractValuesFromUnion or shouldExtractLiteralValuesFromEnum, sorts union members in string-sort order when set to true. This is useful for ensuring the same order of members every time.

skipChildrenPropWithoutDoc: boolean (default: true)

If set to false the docs for the children prop will be generated even without an explicit description.

shouldRemoveUndefinedFromOptional: boolean

If set to true, types that are optional will not display " | undefined" in the type.

savePropValueAsString: boolean

If set to true, defaultValue to props will be string. Example:

Component.defaultProps = {
  counter: 123,
  disabled: false,
};

Will return:

  counter: {
      defaultValue: '123',
      required: true,
      type: 'number'
  },
  disabled: {
      defaultValue: 'false',
      required: true,
      type: 'boolean'
  }

Styled components example:

componentNameResolver: (exp, source) =>
  exp.getName() === "StyledComponentClass" && getDefaultExportForFile(source);

The parser exports getDefaultExportForFile helper through its public API.

Example

In the example folder you can see React Styleguidist integration.

Warning: only named exports are supported. If your project uses default exports, you still need to include named exports for react-docgen-typescript.

The component Column.tsx

import * as React from "react";
import { Component } from "react";

/**
 * Column properties.
 */
export interface IColumnProps {
  /** prop1 description */
  prop1?: string;
  /** prop2 description */
  prop2: number;
  /**
   * prop3 description
   */
  prop3: () => void;
  /** prop4 description */
  prop4: "option1" | "option2" | "option3";
}

/**
 * Form column.
 */
export class Column extends Component<IColumnProps, {}> {
  render() {
    return <div>Test</div>;
  }
}

Will generate the following stylesheet:

Stylesheet example

The functional component Grid.tsx

import * as React from "react";

/**
 * Grid properties.
 */
export interface IGridProps {
  /** prop1 description */
  prop1?: string;
  /** prop2 description */
  prop2: number;
  /**
   * prop3 description
   */
  prop3: () => void;
  /** Working grid description */
  prop4: "option1" | "option2" | "option3";
}

/**
 * Form Grid.
 */
export const Grid = (props: IGridProps) => {
  const smaller = () => {
    return;
  };
  return <div>Grid</div>;
};

Will generate the following stylesheet:

Stylesheet example

Contributions

The typescript is pretty complex and there are many different ways how to define components and their props so it's realy hard to support all these use cases. That means only one thing, contributions are highly welcome. Just keep in mind that each PR should also include tests for the part it's fixing.

Thanks to all contributors without their help there wouldn't be a single bug fixed or feature implemented. Check the contributors tab to find out more. All those people supported this project. THANK YOU!

Thanks to others

The integration with React Styleguidist wouldn't be possible without Vyacheslav Slinko pull request #118 at React Styleguidist.

NPM DownloadsLast 30 Days