CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-docgen

A library to extract information from React components for documentation generation.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

importers.mddocs/

Module Import Resolution

System for resolving module imports and dependencies during component analysis, enabling cross-file component discovery.

Capabilities

Importer Interface

The base interface for all module import resolvers.

type Importer = (
  path: ImportPath,
  name: string,
  file: FileState
) => NodePath | null;

type ImportPath = NodePath<
  ExportAllDeclaration | ExportNamedDeclaration | ImportDeclaration
>;

Parameters:

  • path: AST path of the import/export statement
  • name: The identifier being imported/exported
  • file: Current file state with parsing context

Returns:

  • NodePath: Resolved AST node if found
  • null: If import cannot be resolved

Filesystem Importer

Resolves imports using Node.js filesystem resolution algorithm.

const fsImporter: Importer;

Resolution Algorithm:

  • Uses Node.js require.resolve() logic
  • Supports npm package resolution
  • Handles relative and absolute paths
  • Resolves file extensions (.js, .ts, .jsx, .tsx)
  • Follows package.json main/exports fields

Usage Example:

import { parse, fsImporter } from "react-docgen";

// Component with imports
const componentCode = `
import { Button } from './Button';
import { theme } from '../theme';

export default function App() {
  return <Button theme={theme} />;
}
`;

const docs = parse(componentCode, {
  importer: fsImporter,
  filename: '/path/to/App.jsx'
});

Ignore Importer

Ignores all import resolution, useful for browser environments or when imports are not available.

const ignoreImporter: Importer;

Use Cases:

  • Browser environments without filesystem access
  • Static analysis without dependency resolution
  • Parsing isolated components
  • Performance optimization when imports are not needed

Usage Example:

import { parse, ignoreImporter } from "react-docgen";

// Parse without resolving imports
const docs = parse(componentCode, {
  importer: ignoreImporter
});

Filesystem Importer Factory

Creates customized filesystem importers with specific resolution options.

function makeFsImporter(options?: FsImporterOptions): Importer;

interface FsImporterOptions {
  /** Custom resolve function */
  resolve?: (id: string, basedir: string) => string;
  /** File extensions to resolve */
  extensions?: string[];
  /** Whether to follow symlinks */
  preserveSymlinks?: boolean;
}

Usage Example:

import { makeFsImporter, parse } from "react-docgen";

const customImporter = makeFsImporter({
  extensions: ['.tsx', '.ts', '.jsx', '.js'],
  preserveSymlinks: false
});

const docs = parse(componentCode, {
  importer: customImporter,
  filename: '/path/to/component.tsx'
});

Browser Field Support

React-docgen automatically handles browser field mappings in package.json for browser compatibility.

// Automatic browser field mappings:
const browserMappings = {
  "./dist/importer/fsImporter.js": "./dist/importer/ignoreImporter.js",
  "./src/importer/fsImporter.ts": "./src/importer/ignoreImporter.ts",
  "./dist/importer/makeFsImporter.js": "./dist/importer/makeIgnoreImporter.js",
  "./src/importer/makeFsImporter.ts": "./src/importer/makeIgnoreImporter.ts"
};

When used in browser environments, filesystem-based importers are automatically replaced with ignore-based importers.

Import Resolution Process

The import resolution process follows these steps:

  1. Parse Import Statement: Extract module specifier and imported names
  2. Resolve Module Path: Use importer to find the target file
  3. Parse Target File: Load and parse the resolved file
  4. Extract Exports: Find the requested export in the target file
  5. Return AST Node: Provide the resolved AST node for analysis

Supported Import/Export Patterns:

// Named imports
import { Component } from './Component';
import { Component as MyComponent } from './Component';

// Default imports  
import Component from './Component';

// Namespace imports
import * as Components from './Components';

// Named exports
export { Component };
export { Component as Button };

// Default exports
export default Component;

// Re-exports
export { Component } from './Component';
export * from './Components';

Custom Importer Development

Importers can be customized for specific resolution strategies or environments.

Custom Importer Example:

import type { Importer } from "react-docgen";

const customImporter: Importer = (path, name, file) => {
  // Custom resolution logic
  const modulePath = path.node.source?.value;
  
  if (modulePath?.startsWith('@components/')) {
    // Handle component library imports
    return resolveComponentLibrary(modulePath, name);
  }
  
  if (modulePath?.startsWith('http://')) {
    // Handle remote imports (not recommended for production)
    return resolveRemoteModule(modulePath, name);
  }
  
  // Fallback to default resolution
  return null;
};

// Usage with custom importer
const docs = parse(sourceCode, {
  importer: customImporter
});

Default Importer Configuration

The default importer used when no custom importer is specified.

const defaultImporter: Importer;

The default configuration uses fsImporter with standard Node.js resolution for most environments, with automatic browser field mapping support.

Error Handling

Import resolution errors are handled gracefully:

  • Module Not Found: Returns null, allowing parsing to continue
  • Parse Errors: Logged and ignored, doesn't break main parsing
  • Circular Dependencies: Detected and handled to prevent infinite loops
  • Permission Errors: Handled gracefully in restricted environments

Error Handling Example:

import { parse } from "react-docgen";

const componentWithMissingImport = `
import { MissingComponent } from './does-not-exist';

export default function App() {
  return <MissingComponent />;
}
`;

// Parsing continues even with unresolvable imports
const docs = parse(componentWithMissingImport);
// docs will contain available information, missing imports are ignored

Install with Tessl CLI

npx tessl i tessl/npm-react-docgen

docs

configuration.md

error-handling.md

handlers.md

importers.md

index.md

parsing.md

resolvers.md

utilities.md

tile.json