react-docgen-typescript

repository·master·Indexed 22 days ago

https://github.com/styleguidist/react-docgen-typescript

A TypeScript-based parser for React component properties that extracts documentation from TypeScript definitions instead of propTypes. Optimized for integration with React Styleguidist, it provides utilities like withDefaultConfig, withCompilerOptions, and withCustomConfig to handle tsconfig.json and compiler settings. It supports advanced prop filtering via propFilter, custom component name resolution, and options for extracting literal values from enums and unions.

Tokens
3.6K
Snippets
7
Records
23
Agent score
79%

What's inside react-docgen-typescript

  1. Integrate react-docgen-typescript with React Styleguidist

    master

    To use this parser with React Styleguidist, assign the parser to the propsParser key in your styleguide.config.js.

    Using default configuration:

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

    Using a custom tsconfig file:

    module.exports = {
      propsParser: require("react-docgen-typescript").withCustomConfig(
        "./tsconfig.json",
        [parserOptions]
      ).parse,
    };
  2. Understand the `ComponentDoc` data structure

    master

    The primary output of the parser is an array of ComponentDoc objects. Each object represents a documented component and contains:

    • displayName: The name of the component.
    • description: The JSDoc description.
    • filePath: The absolute path to the file.
    • props: A Props object (a map of PropItems keyed by prop name).
    • methods: An array of Method objects describing component methods.
    • tags: A map of additional JSDoc tags.
  3. Convert default prop values to strings with `savePropValueAsString`

    master

    When savePropValueAsString is set to true, the defaultValue for props is returned as a string instead of its original type.

    Example: If your component has:

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

    The output will be:

      counter: {
          defaultValue: '123',
          required: true,
          type: 'number'
      },
      disabled: {
          defaultValue: 'false',
          required: true,
          type: 'boolean'
      }
  4. Determine component names with componentNameResolver

    master

    When parsing components, react-docgen-typescript uses a componentNameResolver (provided via ParserOptions) to determine the display name of a component. The internal logic follows this priority:

    1. Explicit displayName: It checks for a .displayName property on stateless functions or a displayName class member on stateful components.
    2. Default Export Logic: If the component matches certain known types (like FunctionComponent, StatelessComponent, MemoExoticComponent, etc.), it may fall back to getDefaultExportForFile.
    3. Filename Fallback: getDefaultExportForFile derives a name from the source file's basename. If the file is named index.ts or index.js, it uses the parent directory's name. The resulting identifier is sanitized to remove non-alphanumeric characters at the start and middle.

    You can extend this behavior by providing customComponentTypes in your ParserOptions to include your own component type identifiers.

  5. Understand the `PropItem` data structure

    master

    Each prop in a component is described by a PropItem object, which includes:

    • name: The prop name.
    • required: Boolean indicating if the prop is mandatory.
    • type: A PropItemType containing the type name and potentially literal values.
    • description: The JSDoc description for the prop.
    • defaultValue: The default value extracted from code or JSDoc @default tags.
    • parent: Information about the parent type/file.
    • declarations: An array of ParentType objects where the prop is declared.
  6. Configure prop filtering with `propFilter`

    master

    The propFilter option allows you to omit specific props from the generated documentation. You can provide either a configuration object or a custom function.

    Using a configuration object: Use skipPropsWithName (array of strings or a single string) to exclude specific prop names, or skipPropsWithoutDoc (boolean) to exclude props that lack a doc comment.

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

    Using a custom function: Provide a function with the signature (prop: PropItem, component: Component) => boolean. This is useful for complex logic, such as filtering out props that originate from node_modules.

    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;
      },
    };
  7. Parse React components for docgen information

    master

    Use the parse function to extract documentation information from a component file. You can pass an options object to customize the output.

    const docgen = require("react-docgen-typescript");
    
    const options = {
      savePropValueAsString: true,
    };
    
    // Parse a file for docgen info
    docgen.parse("./path/to/component", options);
  8. Create custom parsers with different configurations

    master

    The package provides several factory functions to create parsers with specific configurations:

    • withDefaultConfig(options): Creates a parser using the default TypeScript configuration combined with your custom docgen options.
    • withCompilerOptions(compilerOptions, options): Creates a parser using custom TypeScript compiler options and custom docgen options.
    • withCustomConfig(tsconfigPath, options): Creates a parser using a specific tsconfig.json file and custom docgen options.
    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,
    });
  9. Configure the parser via `ParserOptions`

    master

    You can fine-tune the extraction process using the ParserOptions object. Key options include:

    • propFilter: A function (props: PropItem, component: Component) => boolean to include or exclude specific props.
    • componentNameResolver: A function to customize how component names are resolved from TypeScript symbols.
    • shouldExtractLiteralValuesFromEnum: Boolean to extract literal values from enums.
    • shouldRemoveUndefinedFromOptional: Boolean to strip | undefined from optional prop types.
    • shouldExtractValuesFromUnion: Boolean to extract values from union types.
    • shouldSortUnions: Boolean to sort union type values.
    • skipChildrenPropWithoutDoc: Boolean (default: true) to skip child props that lack JSDoc.
    • customComponentTypes: An array of strings representing additional component type names to recognize (e.g., ['MyCustomComponent']).
  10. Configure optional prop and children documentation

    master

    Use these options to control how optional props and the children prop are handled:

    • skipChildrenPropWithoutDoc (boolean, default: true): If false, the children prop will be documented even if it lacks an explicit description.
    • shouldRemoveUndefinedFromOptional (boolean): If true, optional types will not display | undefined in the type string.