Install react-docgen-typescript
masterInstall the package as a development dependency using npm.
npm install --save-dev react-docgen-typescriptrepository·master·Indexed 22 days ago
https://github.com/styleguidist/react-docgen-typescriptA 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.
Install the package as a development dependency using npm.
npm install --save-dev react-docgen-typescriptTo 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,
};To run the example project provided in this repository, follow these steps:
npm installnpm starthttp://localhost:6060/.Note: This project was tested against Node.js version v10.0.1.
npm install
npm startThe 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.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'
}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:
displayName: It checks for a .displayName property on stateless functions or a displayName class member on stateful components.FunctionComponent, StatelessComponent, MemoExoticComponent, etc.), it may fall back to getDefaultExportForFile.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.
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.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;
},
};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);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,
});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']).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.