### Parser usage example with TypeScript program Source: https://github.com/styleguidist/react-docgen-typescript Shows how to instantiate Parser with a TypeScript program and options, then iterate over exported symbols to get component documentation via getComponentInfo. Requires a pre-built ts.Program and ParserOptions. ```TypeScript import * as ts from 'typescript'; import { Parser, ComponentDoc } from 'react-docgen-typescript'; const program = ts.createProgram(['./src/components/Column.tsx'], { jsx: ts.JsxEmit.React, esModuleInterop: true }); const parser = new Parser(program, { shouldRemoveUndefinedFromOptional: true }); const sourceFile = program.getSourceFile('./src/components/Column.tsx')!; const moduleSymbol = program.getTypeChecker().getSymbolAtLocation(sourceFile)!; const exports = program.getTypeChecker().getExportsOfModule(moduleSymbol); for (const exp of exports) { const doc: ComponentDoc | null = parser.getComponentInfo(exp, sourceFile); if (doc) console.log(doc.displayName, doc.props); } ``` -------------------------------- ### CommonJS import example Source: https://github.com/styleguidist/react-docgen-typescript Shows how to import the package in CommonJS. The example calls parse() on a file path and creates a parser with withDefaultConfig() using the savePropValueAsString option. ```javascript const docgen = require('react-docgen-typescript'); const docs = docgen.parse('./src/components/Button.tsx'); const parser = docgen.withDefaultConfig({ savePropValueAsString: true }); ``` -------------------------------- ### trimFileName usage examples Source: https://github.com/styleguidist/react-docgen-typescript Shows how to call trimFileName in a monorepo package. The first example is the canonical single-package case. The second example demonstrates Windows path handling with explicit platform and cwd. The third shows that paths with no common ancestor are returned unchanged. ```typescript import { trimFileName } from 'react-docgen-typescript/lib/trimFileName'; // Somewhere in a monorepo package at /repo/packages/ui trimFileName('/repo/packages/ui/node_modules/@types/react/index.d.ts'); // => 'packages/ui/node_modules/@types/react/index.d.ts' trimFileName( 'C:/repo/packages/ui/node_modules/react/index.d.ts', 'C:\\repo\\packages\\ui', 'win32' ); // => 'packages\\ui\\node_modules\\react\\index.d.ts' (slashes restored) // Paths with no common ancestor come back untouched: trimFileName('/tmp/elsewhere/foo.ts', '/repo/packages/ui'); // => '/tmp/elsewhere/foo.ts' ``` -------------------------------- ### ES modules / TypeScript import example Source: https://github.com/styleguidist/react-docgen-typescript Shows how to import the package in ES modules or TypeScript. The example uses withDefaultConfig() with the shouldRemoveUndefinedFromOptional option and calls parse() on a file name. ```typescript import { parse, withDefaultConfig, ParserOptions, ComponentDoc } from 'react-docgen-typescript'; const options: ParserOptions = { shouldRemoveUndefinedFromOptional: true }; const docs: ComponentDoc[] = withDefaultConfig(options).parse('Button.tsx'); ``` -------------------------------- ### Parser options example with withDefaultConfig Source: https://github.com/styleguidist/react-docgen-typescript Shows how to configure parser options such as savePropValueAsString, shouldRemoveUndefinedFromOptional, and propFilter, then parse a component file. ```javascript const docgen = require('react-docgen-typescript'); const options = { savePropValueAsString: true, shouldRemoveUndefinedFromOptional: true, propFilter: { skipPropsWithName: ['as', 'id'], skipPropsWithoutDoc: true } }; const parser = docgen.withDefaultConfig(options); const docs = parser.parse('./src/components/Button.tsx'); ``` -------------------------------- ### withCompilerOptions usage example Source: https://github.com/styleguidist/react-docgen-typescript Shows how to create a parser with custom compiler options and parse a file. Includes imports from 'react-docgen-typescript' and 'typescript'. ```ts import { withCompilerOptions } from 'react-docgen-typescript'; import { JsxEmit, ModuleKind, ScriptTarget } from 'typescript'; const parser = withCompilerOptions( { jsx: JsxEmit.React, module: ModuleKind.ESNext, target: ScriptTarget.ES2019, esModuleInterop: true, baseUrl: './src', paths: { '@components/*': ['components/*'] } }, { savePropValueAsString: true } ); const docs = parser.parse('./src/components/Button.tsx'); ``` -------------------------------- ### Install react-docgen-typescript via npm Source: https://github.com/styleguidist/react-docgen-typescript/blob/master/README.md Install the package as a dev dependency using npm. ```bash npm install --save-dev react-docgen-typescript ``` -------------------------------- ### Usage example: withCustomConfig with tsconfig.json Source: https://github.com/styleguidist/react-docgen-typescript Shows how to create a parser from a tsconfig.json file and parse a component file. The parserOpts argument is required and has no default. ```TypeScript import { withCustomConfig } from 'react-docgen-typescript'; const parser = withCustomConfig('./tsconfig.json', { shouldRemoveUndefinedFromOptional: true }); const docs = parser.parse('./src/components/Button.tsx'); ``` -------------------------------- ### Usage example importing parse from propTypesParser Source: https://github.com/styleguidist/react-docgen-typescript Shows how to import and use the legacy parse from the compiled module. The function is not re-exported from the package entry point, so import from the lib path. The example includes both module syntaxes and a call that is exactly equivalent to the modern parse. ```ts // Either module syntax: import { parse } from 'react-docgen-typescript/lib/propTypesParser'; // const { parse } = require('react-docgen-typescript/lib/propTypesParser'); const docs = parse('./src/components/Column.tsx'); // Exactly equivalent to: react-docgen-typescript.parse('./src/components/Column.tsx') console.log(docs[0].displayName, docs[0].props); ``` -------------------------------- ### Migration example from legacy to modern parse Source: https://github.com/styleguidist/react-docgen-typescript Shows how to migrate from the legacy propTypesParser.parse to the modern parser.parse. The modern API is a strict superset, supporting arrays and options. ```ts import { parse } from 'react-docgen-typescript'; // Old: parse('Column.tsx') -> New: parse('Column.tsx') // Old: (no equivalent) -> New: parse(['A.tsx', 'B.tsx'], options) ``` -------------------------------- ### Usage example for getFullJsDocComment Source: https://github.com/styleguidist/react-docgen-typescript Shows how to call getFullJsDocComment on a symbol and access the returned JSDoc fields: description, tags.default, and fullComment. ```TypeScript const jsdoc = parser.getFullJsDocComment(propSymbol); console.log(jsdoc.description); // "prop1 description" console.log(jsdoc.tags.default); // value of @default tag, if any console.log(jsdoc.fullComment); // "description\n@tag value..." ``` -------------------------------- ### Usage example for getMethodsInfo - TypeScript Source: https://github.com/styleguidist/react-docgen-typescript Shows how to retrieve methods from a component using getComponentInfo and log them. The output demonstrates the structure of the methods array, including a method with a @public tag. ```typescript const doc = parser.getComponentInfo(exp, sourceFile); // Methods documented on the component class with a `@public` tag: console.log(doc?.methods); // { // name: 'myCoolMethod', // docblock: 'My super cool method\n@param myParam Documentation for parameter 1\n@public\n@returns The answer to the universe', // modifiers: [], // params: [ // { name: 'myParam', type: { name: 'number' } }, // { name: 'mySecondParam?', type: { name: 'string | undefined' } } // ], // returns: { description: 'The answer to the universe', type: 'number' } // } ``` -------------------------------- ### withCustomConfig usage in styleguide.config.js Source: https://github.com/styleguidist/react-docgen-typescript Loads a project tsconfig.json and uses its options, with extra parserOpts applied on top. This example shows integration with React Styleguidist's propsParser. Note that parserOpts is a required positional argument for withCustomConfig. ```js // styleguide.config.js (React Styleguidist) module.exports = { propsParser: require('react-docgen-typescript').withCustomConfig( './tsconfig.json', { savePropValueAsString: true } ).parse }; ``` -------------------------------- ### savePropValueAsString example with defaultProps Source: https://github.com/styleguidist/react-docgen-typescript/blob/master/README.md Example showing how defaultProps values are converted to strings when savePropValueAsString is true. The input object has numeric and boolean values, and the output shows them as strings. ```javascript Component.defaultProps = { counter: 123, disabled: false, }; ``` ```javascript counter: { defaultValue: '123', required: true, type: 'number' }, disabled: { defaultValue: 'false', required: true, type: 'boolean' } ``` -------------------------------- ### Usage of extractDefaultPropsFromComponent Source: https://github.com/styleguidist/react-docgen-typescript Shows how to call extractDefaultPropsFromComponent and then pass the resulting defaults to getPropsInfo. The comment shows example output values. ```ts const defaults = parser.extractDefaultPropsFromComponent(symbol, sourceFile); // { sampleFalse: false, sampleNumber: -1, sampleString: 'hello', sampleTrue: true, ... } const props = parser.getPropsInfo(propsType, defaults); ``` -------------------------------- ### Usage example for getComponentInfo Source: https://github.com/styleguidist/react-docgen-typescript Shows how to call `getComponentInfo` with a custom `componentNameResolver` that renames any `default` export to `MyRenamedDefault`. The returned `doc` is `null` for non-components; otherwise `doc.displayName`, `doc.description`, and `doc.props` are available. ```TypeScript import { Parser } from 'react-docgen-typescript'; // exp/source obtained from a ts.Program as shown in the constructor example const doc = parser.getComponentInfo(exp, sourceFile, (symbol, src) => { // Custom naming: always rename anything exported as `default` to the file name return symbol.getName() === 'default' ? 'MyRenamedDefault' : undefined; }); if (doc === null) { console.log('Not a component — skipping'); } else { console.log(doc.displayName, doc.description, doc.props); } ``` -------------------------------- ### Error handling example: withCustomConfig with nonexistent path Source: https://github.com/styleguidist/react-docgen-typescript Demonstrates catching the error thrown when the tsconfig path is invalid. The error message includes the path, error code, and message. Falls back to withDefaultConfig. ```TypeScript import { withCustomConfig } from 'react-docgen-typescript'; let parser; try { parser = withCustomConfig('/nonexistent/tsconfig.json', {}); } catch (error) { // Error: Cannot load custom tsconfig.json from provided path: /nonexistent/tsconfig.json, with error code: 0, message: ... console.error('Falling back to default parser instead'); parser = require('react-docgen-typescript').withDefaultConfig({}); } ``` -------------------------------- ### getTypeSymbol usage example Source: https://github.com/styleguidist/react-docgen-typescript Shows how to call `getTypeSymbol` and check for statically attached sub-components on `typeSymbol.members`. ```ts const typeSymbol = parser.getTypeSymbol(exp); if (typeSymbol?.members) { // statically attached sub-components live on typeSymbol.members } ``` -------------------------------- ### withCompilerOptions usage example Source: https://github.com/styleguidist/react-docgen-typescript Creates a parser with custom TypeScript compiler options. The options object is passed directly to ts.createProgram each time parse is called. The second argument accepts ParserOptions like shouldExtractValuesFromUnion. ```ts import { withCompilerOptions } from 'react-docgen-typescript'; const parser = withCompilerOptions( { jsx: 'react', module: 'esnext', target: 'es2019', esModuleInterop: true }, { shouldExtractValuesFromUnion: true } ); ``` -------------------------------- ### Styled components componentNameResolver example Source: https://github.com/styleguidist/react-docgen-typescript/blob/master/README.md Example of componentNameResolver for styled components. It returns the default export for files where the component name is StyledComponentClass, using the getDefaultExportForFile helper. ```typescript componentNameResolver: (exp, source) => exp.getName() === "StyledComponentClass" && getDefaultExportForFile(source); ``` -------------------------------- ### Error handling example for legacy parse Source: https://github.com/styleguidist/react-docgen-typescript Demonstrates wrapping the legacy parse in a try/catch to handle errors such as syntax errors in the component file that surface through ts.createProgram. On failure, logs the error and sets docs to an empty array. ```ts import { parse } from 'react-docgen-typescript/lib/propTypesParser'; let docs; try { docs = parse('./src/components/Column.tsx'); } catch (error) { // e.g. a syntax error in the component file surfacing through ts.createProgram console.error('Failed to parse component:', error); docs = []; } ``` -------------------------------- ### Component typed with React.HTMLAttributes Source: https://github.com/styleguidist/react-docgen-typescript/blob/master/README.md Example of a component typed with React.HTMLAttributes, which would include many HTML attributes in props documentation unless filtered. ```typescript const MyComponent: React.FC> = ()... ``` -------------------------------- ### getPropMap usage example Source: https://github.com/styleguidist/react-docgen-typescript Evaluates an object literal from a class defaultProps initializer. The result includes only literal values (e.g., a: 1, b: 'x'); identifiers like someRef yield null and are dropped. ```TypeScript // Evaluate `{ a: 1, b: 'x', c: someRef }` from a class defaultProps initializer const map = parser.getPropMap(properties); // { a: 1, b: 'x' } — `someRef` (identifier) yields null and is dropped ``` -------------------------------- ### Usage: parse multiple files with options Source: https://github.com/styleguidist/react-docgen-typescript Example usage of the parse function with multiple files and options. It passes shouldExtractLiteralValuesFromEnum: true and then checks if the icon prop's type is 'enum' to log its values. ```ts import { parse } from 'react-docgen-typescript'; const docs = parse(['./src/components/Button.tsx', './src/components/Input.tsx'], { shouldExtractLiteralValuesFromEnum: true }); // Every prop equals an enum gets a `value` array under `type.value` const iconProp = docs[0].props['icon']; if (iconProp.type.name === 'enum') { console.log(iconProp.type.value.map(v => v.value)); } ``` -------------------------------- ### Usage examples for getDocgenType Source: https://github.com/styleguidist/react-docgen-typescript Shows two usage scenarios: extracting enum values from a union when shouldExtractValuesFromUnion is enabled, and returning a plain type name for a non-union type. The comments show the expected output for each call. ```TypeScript // Union with shouldExtractValuesFromUnion const docgenType = parser.getDocgenType(unionType, false); // docgenType = { name: 'enum', raw: '"a" | "b" | "c"', // value: [{ value: '"a"' }, { value: '"b"' }, { value: '"c"' }] } // Plain type const docgenType2 = parser.getDocgenType(stringType, true); // docgenType2 = { name: 'string' } ``` -------------------------------- ### Direct usage of buildFilter with StaticPropFilter Source: https://github.com/styleguidist/react-docgen-typescript Shows direct use of buildFilter with a StaticPropFilter object. The example sets skipChildrenPropWithoutDoc: false and skipPropsWithName: ['id', 'className'], then filters a fake prop named 'id' which is skipped, logging false. ```TypeScript import { buildFilter } from 'react-docgen-typescript/lib/buildFilter'; import { ParserOptions, PropItem, Component } from 'react-docgen-typescript'; const opts: ParserOptions = { skipChildrenPropWithoutDoc: false, propFilter: { skipPropsWithName: ['id', 'className'] } }; const filter = buildFilter(opts); const fakeProp: PropItem = { name: 'id', required: false, type: { name: 'string' }, description: '', defaultValue: null }; const keep = filter(fakeProp, { name: 'MyComponent' }); console.log(keep); // false — skipped by skipPropsWithName ``` -------------------------------- ### Usage: parse a single file Source: https://github.com/styleguidist/react-docgen-typescript Example usage of the parse function to parse a single file. It imports parse from 'react-docgen-typescript' and logs the displayName and props of the first component. ```ts import { parse } from 'react-docgen-typescript'; const docs = parse('./src/components/Button.tsx'); console.log(docs[0].displayName, docs[0].props); ``` -------------------------------- ### withCustomConfig(tsconfigPath, parserOpts) Source: https://github.com/styleguidist/react-docgen-typescript Creates a FileParser from a tsconfig.json file on disk. Reads the config with ts.readConfigFile, then expands it with ts.parseJsonConfigFileContent. ```APIDOC ## withCustomConfig(tsconfigPath, parserOpts) ### Description Creates a `FileParser` from a `tsconfig.json` file on disk. Reads the config with `ts.readConfigFile`, then expands it with `ts.parseJsonConfigFileContent`. ### Signature ```ts export function withCustomConfig( tsconfigPath: string, parserOpts: ParserOptions ): FileParser ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `tsconfigPath` | `string` | yes | — | Path to the `tsconfig.json` to load; the directory of this file becomes the base path for config expansion | | `parserOpts` | `ParserOptions` | yes | — | Options controlling extraction (note: no default here — it is a required positional argument) | ### Return type `FileParser`. ### Throws | Error type | Condition | |-----------|-----------| | `Error` | `ts.readConfigFile` reports an error (missing/invalid JSON). Message: `Cannot load custom tsconfig.json from provided path: , with error code: , message: ` | | `Error` | `ts.parseJsonConfigFileContent` returns diagnostics; the first error is re-thrown either as-is (if it is an `Error` instance) or with message `TS: ` | ### Usage ```ts import { withCustomConfig } from 'react-docgen-typescript'; const parser = withCustomConfig('./tsconfig.json', { shouldRemoveUndefinedFromOptional: true }); const docs = parser.parse('./src/components/Button.tsx'); ``` Error handling: ```ts import { withCustomConfig } from 'react-docgen-typescript'; let parser; try { parser = withCustomConfig('/nonexistent/tsconfig.json', {}); } catch (error) { // Error: Cannot load custom tsconfig.json from provided path: /nonexistent/tsconfig.json, with error code: 0, message: ... console.error('Falling back to default parser instead'); parser = require('react-docgen-typescript').withDefaultConfig({}); } ``` ``` -------------------------------- ### withDefaultConfig usage in styleguide.config.js Source: https://github.com/styleguidist/react-docgen-typescript Recommended integration point for React Styleguidist's propsParser. Uses propFilter to skip props without documentation. ```js // styleguide.config.js module.exports = { propsParser: require('react-docgen-typescript').withDefaultConfig({ propFilter: { skipPropsWithoutDoc: true } }).parse }; ``` -------------------------------- ### withCompilerOptions(compilerOptions, parserOpts?) Source: https://github.com/styleguidist/react-docgen-typescript Creates a FileParser from an explicit ts.CompilerOptions object, for fine-grained control over how the source file is compiled. ```APIDOC ## withCompilerOptions(compilerOptions, parserOpts?) ### Description Creates a `FileParser` from an explicit `ts.CompilerOptions` object, for fine-grained control over how the source file is compiled. ### Signature ```ts export function withCompilerOptions( compilerOptions: ts.CompilerOptions, parserOpts: ParserOptions = defaultParserOpts ): FileParser { return { parse(filePathOrPaths: string | string[]): ComponentDoc[] { return parseWithProgramProvider( filePathOrPaths, compilerOptions, parserOpts ); }, parseWithProgramProvider(filePathOrPaths, programProvider) { return parseWithProgramProvider( filePathOrPaths, compilerOptions, parserOpts, programProvider ); } }; } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `compilerOptions` | `ts.CompilerOptions` | yes | — | TypeScript compiler options used when creating the program that parses the files | | `parserOpts` | `ParserOptions` | no | `defaultParserOpts` (`{}`) | Options controlling extraction | ### Return type `FileParser` — see [FileParser](#fileparser). ### Usage ```ts import { withCompilerOptions } from 'react-docgen-typescript'; import { JsxEmit, ModuleKind, ScriptTarget } from 'typescript'; const parser = withCompilerOptions( { jsx: JsxEmit.React, module: ModuleKind.ESNext, target: ScriptTarget.ES2019, esModuleInterop: true, baseUrl: './src', paths: { '@components/*': ['components/*'] } }, { savePropValueAsString: true } ); const docs = parser.parse('./src/components/Button.tsx'); ``` ``` -------------------------------- ### withCustomConfig function implementation (src/parser.ts) Source: https://github.com/styleguidist/react-docgen-typescript Exact source of withCustomConfig from src/parser.ts lines 144-177. It reads a tsconfig.json file, expands it with ts.parseJsonConfigFileContent, and returns a FileParser. Throws an Error if the config file cannot be loaded or if parseJsonConfigFileContent returns diagnostics. ```TypeScript /** * Constructs a parser for a specified tsconfig file. */ export function withCustomConfig( tsconfigPath: string, parserOpts: ParserOptions ): FileParser { const basePath = path.dirname(tsconfigPath); const { config, error } = ts.readConfigFile(tsconfigPath, filename => fs.readFileSync(filename, 'utf8') ); if (error !== undefined) { // tslint:disable-next-line: max-line-length const errorText = `Cannot load custom tsconfig.json from provided path: ${tsconfigPath}, with error code: ${error.code}, message: ${error.messageText}`; throw new Error(errorText); } const { options, errors } = ts.parseJsonConfigFileContent( config, ts.sys, basePath, {}, tsconfigPath ); if (errors && errors.length) { if (errors[0] instanceof Error) throw errors[0]; else if (errors[0].messageText) throw new Error(`TS${errors[0].code}: ${errors[0].messageText}`); else throw new Error(JSON.stringify(errors[0])); } return withCompilerOptions(options, parserOpts); } ``` -------------------------------- ### FileParser.parseWithProgramProvider Source: https://github.com/styleguidist/react-docgen-typescript Parses TypeScript files with an optional custom TypeScript program provider. Returns component documentation for the specified files. ```APIDOC ## FileParser.parseWithProgramProvider ### Description Parses TypeScript files with an optional custom TypeScript program provider. Returns component documentation for the specified files. ### Method parseWithProgramProvider ### Endpoint FileParser.parseWithProgramProvider(filePathOrPaths: string | string[], programProvider?: () => ts.Program): ComponentDoc[] ### Parameters #### Arguments - **filePathOrPaths** (string | string[]) - Required - File path or array of file paths to parse - **programProvider** (() => ts.Program) - Optional - Custom TypeScript program provider function ### Response #### Success Response - **ComponentDoc[]** - Array of component documentation objects ``` -------------------------------- ### withDefaultConfig(parserOpts?) Source: https://github.com/styleguidist/react-docgen-typescript Creates a FileParser using the built-in default TypeScript compiler options. This is the recommended integration point for React Styleguidist's propsParser. ```APIDOC ## withDefaultConfig(parserOpts?) ### Description Creates a `FileParser` using the built-in default TypeScript compiler options. ### Signature ```ts export function withDefaultConfig( parserOpts: ParserOptions = defaultParserOpts ): FileParser { return withCompilerOptions(defaultOptions, parserOpts); } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `parserOpts` | `ParserOptions` | no | `defaultParserOpts` (`{}`) | Options controlling extraction | ### Return type `FileParser` — reusable parser object with `.parse()` and `.parseWithProgramProvider()` methods. ### Usage ```js // styleguide.config.js module.exports = { propsParser: require('react-docgen-typescript').withDefaultConfig({ propFilter: { skipPropsWithoutDoc: true } }).parse }; ``` ``` -------------------------------- ### constructor(program, opts) Source: https://github.com/styleguidist/react-docgen-typescript Creates a new Parser instance with a TypeScript program and extraction options. The constructor initializes the type checker and configures all extraction behaviors from the provided options. ```APIDOC ## constructor(program, opts) ### Description Creates a new Parser instance with a TypeScript program and extraction options. The constructor initializes the type checker and configures all extraction behaviors from the provided options. ### Signature ```ts constructor(program: ts.Program, opts: ParserOptions) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `program` | `ts.Program` | yes | — | An already-built TypeScript program whose type checker is used for all analysis | | `opts` | `ParserOptions` | yes | — | Extraction options; each boolean option is coerced with `Boolean(...)`. `propFilter` is compiled to a `PropFilter` via `buildFilter` | ### Return type `Parser` instance. ### Usage ```ts import * as ts from 'typescript'; import { Parser, ComponentDoc } from 'react-docgen-typescript'; const program = ts.createProgram(['./src/components/Column.tsx'], { jsx: ts.JsxEmit.React, esModuleInterop: true }); const parser = new Parser(program, { shouldRemoveUndefinedFromOptional: true }); const sourceFile = program.getSourceFile('./src/components/Column.tsx')!; const moduleSymbol = program.getTypeChecker().getSymbolAtLocation(sourceFile)!; const exports = program.getTypeChecker().getExportsOfModule(moduleSymbol); for (const exp of exports) { const doc: ComponentDoc | null = parser.getComponentInfo(exp, sourceFile); if (doc) console.log(doc.displayName, doc.props); } ``` ``` -------------------------------- ### Integrate with React Styleguidist using withCustomConfig Source: https://github.com/styleguidist/react-docgen-typescript/blob/master/README.md Configure styleguide.config.js to use react-docgen-typescript as the propsParser with a custom tsconfig file and parser options. ```javascript module.exports = { propsParser: require("react-docgen-typescript").withCustomConfig( "./tsconfig.json", [parserOptions] ).parse, }; ``` -------------------------------- ### Usage with parseWithProgramProvider Source: https://github.com/styleguidist/react-docgen-typescript Shows how to create a parser with withCompilerOptions and reuse an existing TypeScript program via parseWithProgramProvider to avoid re-compiling shared projects. The provider is optional; without it, a new program is created from the file paths and compiler options. ```ts import * as ts from 'typescript'; import { withCompilerOptions } from 'react-docgen-typescript'; const rootNames = ['./src/components/Button.tsx']; const compilerOptions = { jsx: ts.JsxEmit.React, esModuleInterop: true }; const parser = withCompilerOptions(compilerOptions); // Reuse a program you already created — avoids re-compiling shared projects const existingProgram = ts.createProgram(rootNames, compilerOptions); const docs = parser.parseWithProgramProvider(rootNames, () => existingProgram); // parseWithProgramProvider also works without provider: parser.parseWithProgramProvider(rootNames) ``` -------------------------------- ### FileParser.parse Source: https://github.com/styleguidist/react-docgen-typescript Parses TypeScript files and returns component documentation. Accepts a single file path or an array of file paths. ```APIDOC ## FileParser.parse ### Description Parses TypeScript files and returns component documentation. Accepts a single file path or an array of file paths. ### Method parse ### Endpoint FileParser.parse(filePathOrPaths: string | string[]): ComponentDoc[] ### Parameters #### Arguments - **filePathOrPaths** (string | string[]) - Required - File path or array of file paths to parse ### Response #### Success Response - **ComponentDoc[]** - Array of component documentation objects ``` -------------------------------- ### Integrate with React Styleguidist using withDefaultConfig Source: https://github.com/styleguidist/react-docgen-typescript/blob/master/README.md Configure styleguide.config.js to use react-docgen-typescript as the propsParser with default TypeScript config and custom parser options. ```javascript module.exports = { propsParser: require("react-docgen-typescript").withDefaultConfig([ parserOptions, ]).parse, }; ``` -------------------------------- ### parseWithProgramProvider(filePathOrPaths, programProvider?) Source: https://github.com/styleguidist/react-docgen-typescript Same as `parse` but allows supplying a provider for an existing `ts.Program`. When the provider is omitted, a new program is created from the file paths and the factory's compiler options. ```APIDOC ## parseWithProgramProvider(filePathOrPaths, programProvider?) ### Description Same as `parse` but allows supplying a provider for an existing `ts.Program`. When the provider is omitted, a new program is created from the file paths and the factory's compiler options. ### Method parseWithProgramProvider ### Parameters #### Arguments - **filePathOrPaths** (string | string[]) - Required - The file path or array of file paths to parse. - **programProvider** (() => ts.Program) - Optional - A function that returns an existing `ts.Program` to reuse. ### Returns - **ComponentDoc[]** - The resulting documentation for the parsed components. ### Request Example ```ts import * as ts from 'typescript'; import { withCompilerOptions } from 'react-docgen-typescript'; const rootNames = ['./src/components/Button.tsx']; const compilerOptions = { jsx: ts.JsxEmit.React, esModuleInterop: true }; const parser = withCompilerOptions(compilerOptions); // Reuse a program you already created — avoids re-compiling shared projects const existingProgram = ts.createProgram(rootNames, compilerOptions); const docs = parser.parseWithProgramProvider(rootNames, () => existingProgram); // parseWithProgramProvider also works without provider: parser.parseWithProgramProvider(rootNames) ``` ``` -------------------------------- ### Create custom parsers with withDefaultConfig, withCompilerOptions, and withCustomConfig Source: https://github.com/styleguidist/react-docgen-typescript/blob/master/README.md Shows how to create parsers with custom TypeScript compiler options or docgen options. withDefaultConfig uses default TypeScript config, withCompilerOptions accepts custom compiler options, and withCustomConfig reads a tsconfig.json file. ```ts 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, }); ``` -------------------------------- ### Usage: combined stateless and stateful props extraction Source: https://github.com/styleguidist/react-docgen-typescript Shows how to obtain the props symbol for any component type by trying stateless first, then stateful. If a props symbol is found, it passes it to getPropsInfo and logs the result. ```ts // The props symbol for any component type: const propsType = parser.extractPropsFromTypeIfStatelessComponent(type) || parser.extractPropsFromTypeIfStatefulComponent(type); if (propsType) { const props = parser.getPropsInfo(propsType); console.log(props); } ``` -------------------------------- ### defaultParserOpts constant Source: https://github.com/styleguidist/react-docgen-typescript Default ParserOptions, an empty object with no options enabled. ```ts export const defaultParserOpts: ParserOptions = {}; ``` -------------------------------- ### parse(fileName) Source: https://github.com/styleguidist/react-docgen-typescript A backward-compatibility shim over the modern parse method. This function parses a single component file and returns documentation for each detected component. It exists only for backward compatibility; use the modern parse method from the parser file for new code. ```APIDOC ## parse(fileName) ### Description A backward-compatibility shim over the modern `parse` method. This function parses a single component file and returns documentation for each detected component. It exists only for backward compatibility; use the modern `parse` method from the parser file for new code. ### Signature ```ts export function parse(fileName: string) { return newParse(fileName); } ``` ### Parameters - **fileName** (string) - Required - Path of the component file to parse. Single string only — unlike the modern `parse`, this wrapper does not accept an array of paths nor `ParserOptions`. ### Return Type `ComponentDoc[]` — the same shape the modern `parse` produces: one entry per detected component in the file. ### Throws - **Error** - Anything thrown by `parser.parse`, e.g. TypeScript compiler errors raised while building the `ts.Program` for a file that cannot be read or compiled. ### Usage Example ```ts // Either module syntax: import { parse } from 'react-docgen-typescript/lib/propTypesParser'; // const { parse } = require('react-docgen-typescript/lib/propTypesParser'); const docs = parse('./src/components/Column.tsx'); // Exactly equivalent to: react-docgen-typescript.parse('./src/components/Column.tsx') console.log(docs[0].displayName, docs[0].props); ``` ### Error Handling Example ```ts import { parse } from 'react-docgen-typescript/lib/propTypesParser'; let docs; try { docs = parse('./src/components/Column.tsx'); } catch (error) { // e.g. a syntax error in the component file surfacing through ts.createProgram console.error('Failed to parse component:', error); docs = []; } ``` ### Migration Note Prefer the modern entry point for new code; it is a strict superset: ```ts import { parse } from 'react-docgen-typescript'; // Old: parse('Column.tsx') -> New: parse('Column.tsx') // Old: (no equivalent) -> New: parse(['A.tsx', 'B.tsx'], options) ``` ``` -------------------------------- ### getComponentInfo(exp, source, componentNameResolver?, customComponentTypes?) Source: https://github.com/styleguidist/react-docgen-typescript The main entry point for extracting a `ComponentDoc` from a single symbol. Returns `null` for symbols that are not components (or that the filter rejects). Results are cached per `${filePath}_${originalName}`. ```APIDOC ## getComponentInfo(exp, source, componentNameResolver?, customComponentTypes?) ### Description The main entry point for extracting a `ComponentDoc` from a single symbol. Returns `null` for symbols that are not components (or that the filter rejects). Results are cached per `${filePath}_${originalName}`. ### Method public method ### Signature ```ts public getComponentInfo( exp: ts.Symbol, source: ts.SourceFile, componentNameResolver: ComponentNameResolver = () => undefined, customComponentTypes: ParserOptions['customComponentTypes'] = [] ): ComponentDoc | null { ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `exp` | `ts.Symbol` | yes | — | Exported symbol to analyze (component function/class or an alias of one) | | `source` | `ts.SourceFile` | yes | — | Source file the symbol was exported from; used for file path, display-name computation and default-props extraction | | `componentNameResolver` | `ComponentNameResolver` | no | `() => undefined` | If it returns a string, that becomes the `displayName`; otherwise fallback naming logic applies | | `customComponentTypes` | `string[]` | no | `[]` | Extra component type names (beyond the built-in list: `__function`, `StatelessComponent`, `Stateless`, `StyledComponentClass`, `StyledComponent`, `IStyledComponent`, `FunctionComponent`, `ForwardRefExoticComponent`, `MemoExoticComponent`) that should have doc comments pulled from their aliases | ### Return type `ComponentDoc | null` — `null` when the symbol has no value declaration and no type symbol, when the export is a PropTypes `Requireable`/`Validator`, when a props type cannot be found and there is no description, or when the doc comment source has no value declaration. When `shouldIncludeExpression` is true and a doc is produced, `expression`/`rootExpression` are attached to the `ComponentDoc`. ### Component name resolution order 1. `componentNameResolver(nameSource, source)` result, else 2. the `@visibleName` JSDoc tag, else 3. `computeComponentName` (a `.displayName` static property, else the export name, else `getDefaultExportForFile` for generic names like `default`, `__function`, `StyledComponentClass`, ... plus `customComponentTypes`). ### Usage ```ts import { Parser } from 'react-docgen-typescript'; // exp/source obtained from a ts.Program as shown in the constructor example const doc = parser.getComponentInfo(exp, sourceFile, (symbol, src) => { // Custom naming: always rename anything exported as `default` to the file name return symbol.getName() === 'default' ? 'MyRenamedDefault' : undefined; }); if (doc === null) { console.log('Not a component — skipping'); } else { console.log(doc.displayName, doc.description, doc.props); } ``` ``` -------------------------------- ### withCompilerOptions function signature Source: https://github.com/styleguidist/react-docgen-typescript Exact source of withCompilerOptions from src/parser.ts lines 180-217. Creates a FileParser from explicit ts.CompilerOptions for fine-grained control. ```ts /** * Constructs a parser for a specified set of TS compiler options. */ export function withCompilerOptions( compilerOptions: ts.CompilerOptions, parserOpts: ParserOptions = defaultParserOpts ): FileParser { return { parse(filePathOrPaths: string | string[]): ComponentDoc[] { return parseWithProgramProvider( filePathOrPaths, compilerOptions, parserOpts ); }, parseWithProgramProvider(filePathOrPaths, programProvider) { return parseWithProgramProvider( filePathOrPaths, compilerOptions, parserOpts, programProvider ); } }; } ``` -------------------------------- ### getComponentExports(exp) Source: https://github.com/styleguidist/react-docgen-typescript Attempts to gather a symbol's exports, resolving aliases if necessary. Returns the resolved symbol and its export table, or undefined if no exports exist. ```APIDOC ## getComponentExports(exp) ### Description Attempts to gather a symbol's exports. Some symbols like `default` exports are aliased, so we need to get the real symbol. ### Method public method ### Signature ```ts public getComponentExports(exp: ts.Symbol) { let targetSymbol = exp; if (targetSymbol.exports) { return { symbol: targetSymbol, exports: targetSymbol.exports! }; } if (exp.flags & ts.SymbolFlags.Alias) { targetSymbol = this.checker.getAliasedSymbol(exp); } if (targetSymbol.exports) { return { symbol: targetSymbol, exports: targetSymbol.exports }; } } ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `exp` | `ts.Symbol` | yes | — | Export symbol (possibly an alias, e.g. a `default` export) | ### Return type `{ symbol: ts.Symbol; exports: ts.SymbolTable } | undefined` — the resolved symbol and its export table, or `undefined` when the symbol has no exports even after alias resolution. Used to discover static sub-components (e.g. `Button.Group`). ``` -------------------------------- ### getFullJsDocComment(symbol) implementation Source: https://github.com/styleguidist/react-docgen-typescript Rebuilds the full JSDoc comment from the pieces TypeScript splits into documentation text and tags. Returns an object with description, fullComment, and tags; the default and type tags appear in tags but not in fullComment. ```TypeScript /** * Extracts a full JsDoc comment from a symbol, even * though TypeScript has broken down the JsDoc comment into plain * text and JsDoc tags. */ public getFullJsDocComment(symbol: ts.Symbol): JSDoc { // in some cases this can be undefined (Pick) if (symbol.getDocumentationComment === undefined) { return defaultJSDoc; } let mainComment = ts.displayPartsToString( symbol.getDocumentationComment(this.checker) ); if (mainComment) { mainComment = mainComment.replace(/\r\n/g, '\n'); } const tags = symbol.getJsDocTags() || []; const tagComments: string[] = []; const tagMap: StringIndexedObject = {}; tags.forEach(tag => { const trimmedText = ts.displayPartsToString(tag.text).trim(); const currentValue = tagMap[tag.name]; tagMap[tag.name] = currentValue ? currentValue + '\n' + trimmedText : trimmedText; if (['default', 'type'].indexOf(tag.name) < 0) { tagComments.push(formatTag(tag)); } }); return { description: mainComment, fullComment: (mainComment + '\n' + tagComments.join('\n')).trim(), tags: tagMap }; } ``` -------------------------------- ### Catch withCustomConfig config content diagnostics Source: https://github.com/styleguidist/react-docgen-typescript Handle errors from ts.parseJsonConfigFileContent. The thrown error is either the original Error instance, a new Error with message 'TS: ', or a JSON string of the diagnostic. ```ts try { parser = withCustomConfig('./tsconfig.json', {}); } catch (error) { // Either the original Error instance, "TS: ", or a JSON string console.error('Configuration problem:', error instanceof Error ? error.message : error); // e.g. "TS5053: Option 'tsBuildInfoFile' cannot be specified without specifying option 'incremental'." } ``` -------------------------------- ### parse(filePathOrPaths, parserOpts?) Source: https://github.com/styleguidist/react-docgen-typescript Parses a file or array of files using default TypeScript compiler options and returns documentation for every React component found. This is the primary entry point for extracting component documentation. ```APIDOC ## parse(filePathOrPaths, parserOpts?) ### Description Parses a file (or array of files) using the built-in default TypeScript compiler options and returns documentation for every React component found. ### Method Function call ### Endpoint `parse(filePathOrPaths, parserOpts?)` ### Parameters #### Function Parameters - **filePathOrPaths** (`string | string[]`) - Required - File path(s) of the component source file(s) to parse - **parserOpts** (`ParserOptions`) - Optional - Options controlling extraction (see configuration.md). Default: `defaultParserOpts` (`{}`) ### Return Type `ComponentDoc[]` — one `ComponentDoc` per detected component, in the order they occur in the module. ### Throws - `Error` - Propagated from the underlying `ts.createProgram` when the source file cannot be compiled ### Request Example ```ts import { parse } from 'react-docgen-typescript'; const docs = parse('./src/components/Button.tsx'); console.log(docs[0].displayName, docs[0].props); ``` Multiple files with options: ```ts import { parse } from 'react-docgen-typescript'; const docs = parse(['./src/components/Button.tsx', './src/components/Input.tsx'], { shouldExtractLiteralValuesFromEnum: true }); // Every prop equals an enum gets a `value` array under `type.value` const iconProp = docs[0].props['icon']; if (iconProp.type.name === 'enum') { console.log(iconProp.type.value.map(v => v.value)); } ``` ``` -------------------------------- ### Module docstring for propTypesParser.ts Source: https://github.com/styleguidist/react-docgen-typescript Exact source docstring for the legacy module, indicating it exists only for backward compatibility and directing users to the modern parser. ```ts /** * This method exists for backward compatibility only. * Use *parse* method from *parser* file. */ ``` -------------------------------- ### ParserOptions Source: https://github.com/styleguidist/react-docgen-typescript Configuration options for the react-docgen-typescript parser. These options control how props are filtered, how component names are resolved, and how types are extracted and formatted. ```APIDOC ## ParserOptions ### Description Configuration options for the react-docgen-typescript parser. These options control how props are filtered, how component names are resolved, and how types are extracted and formatted. ### Fields - **propFilter** (`StaticPropFilter | PropFilter`) - Optional - Static filter object or predicate function; see configuration.md - **componentNameResolver** (`ComponentNameResolver`) - Optional - Custom display-name function - **shouldExtractLiteralValuesFromEnum** (`boolean`) - Optional - Convert string/number/enum/undefined-literal unions to docgen enum format - **shouldRemoveUndefinedFromOptional** (`boolean`) - Optional - Strip `| undefined` from optional prop types - **shouldExtractValuesFromUnion** (`boolean`) - Optional - Convert every union to docgen enum format - **shouldSortUnions** (`boolean`) - Optional - Sort extracted union members in string order - **skipChildrenPropWithoutDoc** (`boolean`) - Optional - `false` keeps undocumented `children` (default behavior drops it) - **savePropValueAsString** (`boolean`) - Optional - Store default values as strings - **shouldIncludePropTagMap** (`boolean`) - Optional - Add `tags` to `PropItem` and use raw description - **shouldIncludeExpression** (`boolean`) - Optional - Attach `ts.Symbol` expressions to `ComponentDoc` - **customComponentTypes** (`string[]`) - Optional - Extra component type names treated like `FunctionComponent` etc. ### Usage Accepted by: `parse`, `withCompilerOptions`, `withDefaultConfig`, `withCustomConfig`, `Parser` constructor. Re-exported from `index.ts`. ```