### Install Dependencies
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/README.md
Installs project dependencies using pnpm. Run this command before starting the development server.
```bash
pnpm install
```
--------------------------------
### Start Development Server
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/README.md
Starts the development server for the react-docgen website. Visit localhost:3000 after running this command.
```bash
pnpm dev
```
--------------------------------
### Install CLI using pnpm
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/cli/page.mdx
Install the react-docgen CLI as a project dependency using pnpm.
```shell
pnpm add @react-docgen/cli
```
--------------------------------
### Install CLI using npm
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/cli/page.mdx
Install the react-docgen CLI as a project dependency using npm.
```shell
npm install --save @react-docgen/cli
```
--------------------------------
### ChainResolver Example
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/resolvers/chain-resolver/page.mdx
An example demonstrating how to use ChainResolver with other builtin resolvers.
```APIDOC
## Example Usage
```ts filename="resolver.ts"
import { builtinResolvers } from 'react-docgen';
const {
ChainResolver,
FindAnnotatedDefinitionsResolver,
FindExportedDefinitionsResolver,
} = builtinResolvers;
const resolver = new ChainResolver(
[
new FindExportedDefinitionsResolver({ limit: 1 }),
new FindAnnotatedDefinitionsResolver(),
],
{ chainingLogic: ChainResolver.Logic.ALL },
);
```
```
--------------------------------
### Install react-docgen with yarn
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/nodejs/page.mdx
Install the react-docgen module using yarn. This command adds the package as a dependency to your project.
```shell
yarn add react-docgen
```
--------------------------------
### Install react-docgen with npm
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/nodejs/page.mdx
Install the react-docgen module using npm. This command adds the package as a dependency to your project.
```shell
npm install --save react-docgen
```
--------------------------------
### Install react-docgen with pnpm
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/nodejs/page.mdx
Install the react-docgen module using pnpm. This command adds the package as a dependency to your project.
```shell
pnpm add react-docgen
```
--------------------------------
### Run CLI without installation using pnpm
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/cli/page.mdx
Use this command to execute the react-docgen CLI directly without any prior installation using pnpm.
```shell
pnpm dlx @react-docgen/cli --help
```
--------------------------------
### Composes Example
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/documentation/basic/page.mdx
Illustrates the 'composes' property, which lists unresolved composed types.
```json
{
"composes": ["./sharedProps"]
}
```
--------------------------------
### Run CLI without installation using npx
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/cli/page.mdx
Use this command to execute the react-docgen CLI directly without any prior installation using npx.
```shell
npx @react-docgen/cli --help
```
--------------------------------
### TypeScript Component Example
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/code-type-handler/page.mdx
This TypeScript component demonstrates the input format for the codeTypeHandler. It includes an interface for props with a description and an optional property.
```typescript
import React from 'react';
interface Props {
/** Text shown inside the button. */
label: string;
disabled?: boolean;
}
export function Button(props: Props) {
return ;
}
```
--------------------------------
### Run CLI without installation using yarn
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/cli/page.mdx
Use this command to execute the react-docgen CLI directly without any prior installation using yarn.
```shell
yarn dlx @react-docgen/cli --help
```
--------------------------------
### Find All Component Definitions in a File
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/resolvers/find-all-definitions-resolver/page.mdx
When the FindAllDefinitionsResolver is active, both components in this file are returned. This example demonstrates how both a function component and a class component are detected.
```typescript
import React from 'react';
function Button() {
return ;
}
class Link extends React.Component {
render() {
return ;
}
}
```
--------------------------------
### CLI Usage with Multiple Glob Patterns
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/cli/page.mdx
Specify at least one glob pattern to search for files. This example demonstrates using multiple glob patterns to include different file types and directories.
```shell
# All .ts or .tsx files in src/ or any .js files in components/
react-docgen "src/**/*.ts?(x) components/**/*.js"
```
--------------------------------
### Component with Docblock
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/component-docblock-handler/page.mdx
This example shows a React component with a JSDoc comment that will be processed by the componentDocblockHandler.
```typescript
/**
* This is my component and this is its description.
*/
() =>
;
```
--------------------------------
### Configure ChainResolver with Multiple Strategies
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/resolvers/chain-resolver/page.mdx
Example of creating a ChainResolver that uses both FindExportedDefinitionsResolver and FindAnnotatedDefinitionsResolver, combining all unique results.
```typescript
import {
builtinResolvers,
} from 'react-docgen';
const {
ChainResolver,
FindAnnotatedDefinitionsResolver,
FindExportedDefinitionsResolver,
} = builtinResolvers;
const resolver = new ChainResolver(
[
new FindExportedDefinitionsResolver({ limit: 1 }),
new FindAnnotatedDefinitionsResolver(),
],
{ chainingLogic: ChainResolver.Logic.ALL },
);
```
--------------------------------
### CLI Importer Usage
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/extending/importer/page.mdx
Shows how to specify an importer using the react-docgen CLI. This example uses the 'ignoreImporter' built-in.
```shell
react-docgen --importer ignoreImporter ./src/Button.tsx
```
--------------------------------
### PropTypeHandler Output Example
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/prop-type-handler/page.mdx
This JSON output represents the structure generated by the propTypeHandler for components defining 'foo' as a string and 'bar' as a required number.
```json
[
{
"props": {
"foo": {
"type": {
"name": "string"
},
"required": false
},
"bar": {
"type": {
"name": "number"
},
"required": true
}
}
}
]
```
--------------------------------
### displayNameHandler Output Example
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/display-name-handler/page.mdx
This JSON output represents the result of the `displayNameHandler` processing a component, showing the identified display name.
```json
[
{
"displayName": "DisplayName"
}
]
```
--------------------------------
### Class Component with contextTypes
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/context-type-handler/page.mdx
Example of defining contextTypes in a legacy React class component. Ensure PropTypes are imported.
```typescript
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
static contextTypes = {
theme: PropTypes.string,
disabled: PropTypes.bool.isRequired,
};
render() {
return ;
}
}
```
--------------------------------
### Writing data with DocumentationBuilder
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/extending/handler/page.mdx
Use methods on `DocumentationBuilder` to add data like display name, composes information, and prop descriptions. You can also get and modify existing prop descriptors.
```typescript
documentation.set('displayName', 'Button');
documentation.addComposes('./otherProps');
const prop = documentation.getPropDescriptor('label');
prop.description = 'Text shown inside the button.';
```
```typescript
documentation.getContextDescriptor('theme');
documentation.getChildContextDescriptor('theme');
```
--------------------------------
### Export Default Component
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/resolvers/find-exported-definitions-resolver/page.mdx
Example of exporting a React component using ES module default export syntax.
```typescript
import React from 'react';
export default function Button() {
return ;
}
```
--------------------------------
### Simple PropTypes Declarations
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/documentation/prop-types/page.mdx
Example of defining simple string and boolean PropTypes for a component. The 'isRequired' flag is also demonstrated.
```typescript
Button.propTypes = {
label: PropTypes.string,
disabled: PropTypes.bool.isRequired,
};
```
```json
{
"label": {
"type": {
"name": "string"
},
"required": false
},
"disabled": {
"type": {
"name": "bool"
},
"required": true
}
}
```
--------------------------------
### Export Component via CommonJS
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/resolvers/find-exported-definitions-resolver/page.mdx
Example of exporting a React component using CommonJS module.exports syntax.
```typescript
import React from 'react';
const Button = () => ;
module.exports = Button;
```
--------------------------------
### Function Component with contextTypes
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/context-type-handler/page.mdx
Example of defining contextTypes for a legacy React function component. Ensure PropTypes are imported.
```typescript
import PropTypes from 'prop-types';
function MyComponent() {
return ;
}
MyComponent.contextTypes = {
theme: PropTypes.string,
disabled: PropTypes.bool.isRequired,
};
```
--------------------------------
### Example React Component with Flow Props
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/documentation/flow/page.mdx
A React component `Button` defined with Flow types for its props. This demonstrates how to annotate component props using Flow syntax.
```javascript
type Props = {
label: string,
disabled?: boolean,
size: 'small' | 'large',
};
export function Button(props: Props) {
return ;
}
```
--------------------------------
### codeTypeHandler Output Example
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/code-type-handler/page.mdx
This JSON represents the output generated by the codeTypeHandler for the provided TypeScript component. It details each prop, its required status, TypeScript type, and description.
```json
[
{
"props": {
"label": {
"required": true,
"tsType": {
"name": "string"
},
"description": "Text shown inside the button."
},
"disabled": {
"required": false,
"tsType": {
"name": "boolean"
},
"description": ""
}
}
}
]
```
--------------------------------
### Class Component Prop Types with Docblock
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/prop-docblock-handler/page.mdx
This example shows how propDocblockHandler processes a React class component with static propTypes and JSDoc comments for prop descriptions.
```typescript
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
static propTypes = {
/** Foo */
foo: PropTypes.string,
bar: PropTypes.number,
};
render() {
return ;
}
}
```
--------------------------------
### Class Component with Assigned propTypes
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/prop-type-handler/page.mdx
This example shows the propTypeHandler detecting prop types assigned directly to the `propTypes` property of a class component. PropTypes must be imported.
```typescript
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
render() {
return ;
}
}
MyComponent.propTypes = {
foo: PropTypes.string,
bar: PropTypes.number.isRequired,
};
```
--------------------------------
### React Component with TypeScript Props
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/documentation/typescript/page.mdx
An example of a React Button component defined with TypeScript props. This demonstrates how to use TypeScript interfaces for component props.
```typescript
interface Props {
label: string;
disabled?: boolean;
size: 'small' | 'large';
}
export function Button(props: Props) {
return ;
}
```
--------------------------------
### Function Component with Destructured Default Props
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/default-props-handler/page.mdx
Example of a function component using default values in prop destructuring, which the handler recognizes.
```typescript
({ a = '1' }) => ;
```
--------------------------------
### Class Component with Spread PropTypes
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/prop-type-composition-handler/page.mdx
Example of a class component where propTypes are defined using a spread operator with an external propTypes object. This handler will capture the imported module name.
```typescript
import otherPropTypes from './Link.js';
import { Component } from 'react';
class Button extends Component {
static propTypes = {
...otherPropTypes,
};
render() {
return ;
}
}
```
--------------------------------
### Create a Filesystem Importer
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/extending/importer/page.mdx
Demonstrates how to create a new filesystem importer using makeFsImporter. This importer can then be used with the parse function to resolve module references.
```typescript
import { makeFsImporter, parse } from 'react-docgen';
const importer = makeFsImporter();
parse(code, {
filename: '/absolute/path/Button.tsx',
importer,
});
```
--------------------------------
### Analyze multiple component files
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/cli/page.mdx
Analyze multiple component files at once by listing their paths.
```shell
react-docgen ./src/components/Button.tsx ./src/components/Label.tsx
```
--------------------------------
### New CLI Package Introduction
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/cli/page.mdx
Introduces the new @react-docgen/cli package, a complete rewrite with significant differences from the old CLI. It no longer supports stdin input and uses globs for path arguments.
```bash
react-docgen --help
```
--------------------------------
### FileState Methods
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/file-state/page.mdx
This section details the methods available on the FileState object.
```APIDOC
## import
### Description
Imports a module at the specified path and returns its AST node path.
### Signature
`fileState.import(path: ImportPath, name: string): NodePath | null`
## parse
### Description
Parses a string of code into a FileState object.
### Signature
`parse(code: string, filename: string): FileState`
## traverse
### Description
Traverses the AST of the file using the provided visitors and state.
### Signature
`traverse(visitors: Visitor, state?: S): void`
```
--------------------------------
### Analyze a single component file
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/cli/page.mdx
Provide a glob or path to a file containing a React component to generate documentation. The result is printed to stdout, and errors/warnings to stderr.
```shell
react-docgen ./src/components/Button.tsx
```
--------------------------------
### New CLI Package and Features
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/cli/page.mdx
Introduces the new `@react-docgen/cli` package, a complete rewrite with significant changes from the previous `react-docgen` CLI. Key differences include glob path arguments, removal of stdin support, and new options like `--handler` and `--importer`.
```bash
react-docgen --handler my-handler --importer my-importer "src/**/*.js"
```
--------------------------------
### Analyze component files using a glob pattern
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/cli/page.mdx
Use a glob pattern to include multiple component files for analysis.
```shell
react-docgen ./src/components/**/*.tsx
```
--------------------------------
### Chaining Multiple Resolvers
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/cli/page.mdx
The `--resolver` option can now be used multiple times. Resolvers will be chained in the defined order, and all components from all resolvers will be used.
```bash
react-docgen --resolver find-all-modules --resolver find-all-react
```
--------------------------------
### Configure ChainResolver with Chaining Logic
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/react-docgen/page.mdx
Demonstrates how to configure the ChainResolver with different chaining logic options like ALL or FIRST_FOUND.
```typescript
import { builtinResolvers } from 'react-docgen';
const { ChainResolver } = builtinResolvers;
const resolver = new ChainResolver([resolver1, resolver2], {
chainingLogic: ChainResolver.Logic.ALL, // or ChainResolver.Logic.FIRST_FOUND,
});
```
--------------------------------
### Create Filesystem Importer
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/api/page.mdx
Use `makeFsImporter` to create a filesystem importer. This is useful for managing separate importer caches or providing a custom module lookup function.
```typescript
import { makeFsImporter } from 'react-docgen';
const importer = makeFsImporter();
```
--------------------------------
### Implement Custom Resolvers (Function and Class)
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/react-docgen/page.mdx
Shows how to implement custom resolvers, supporting both function-based and class-based approaches for resolving components.
```typescript
import type { ResolverClass, ResolverFunction } from 'react-docgen';
// This was the only option until now
const functionResolver: ResolverFunction = (file: FileState) => {
//needs to return array of found components
};
// This is the new class resolver
class MyResolver implements ResolverClass {
resolve(file: FileState) {
//needs to return array of found components
}
}
const classResolver = new MyResolver();
```
--------------------------------
### Renamed Resolver: findAllComponentDefinitions
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/migrate/v6/page.mdx
The `findAllComponentDefinitions` resolver is now a class and must be instantiated. Use `builtinResolvers` to access it.
```diff
-const resolver = builtinResolvers.findAllComponentDefinitions
+const resolver = new builtinResolvers.FindAllDefinitionsResolver()
```
--------------------------------
### Using a custom handler via CLI
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/extending/handler/page.mdx
The CLI allows you to specify a custom handler by its path or package name using the `--handler` flag.
```shell
react-docgen --handler ./myHandler.js ./src/Button.tsx
```
--------------------------------
### makeFsImporter
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/api/page.mdx
Creates a filesystem importer. This is useful when you want separate importer caches or a custom module lookup function.
```APIDOC
## makeFsImporter
### Description
Creates a filesystem importer. This is useful when you want separate importer caches, or when you want to provide a custom module lookup function.
### Usage
```typescript
import { makeFsImporter } from 'react-docgen';
const importer = makeFsImporter();
```
```
--------------------------------
### Generated Documentation Output for contextTypes
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/context-type-handler/page.mdx
The expected JSON output structure for contextTypes processed by the contextTypeHandler.
```json
[
{
"context": {
"theme": {
"type": {
"name": "string"
},
"required": false
},
"disabled": {
"type": {
"name": "bool"
},
"required": true
}
}
}
]
```
--------------------------------
### Using a Custom Resolver with react-docgen CLI
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/extending/resolver/page.mdx
The react-docgen CLI supports loading custom resolvers via the `--resolver` flag, accepting paths to local files or package names.
```shell
react-docgen --resolver ./myResolver.js ./src/Button.tsx
```
--------------------------------
### Output analysis to a file
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/cli/page.mdx
Direct the output of the analysis to a specified file instead of stdout. Warnings and errors will still be written to stderr.
```shell
react-docgen -o output.json ./src/components/Button.tsx
```
--------------------------------
### Migrating to Class-Based Resolvers
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/react-docgen/page.mdx
Demonstrates the migration from function-based resolvers to class-based resolvers in react-docgen. Use this when updating older codebases to the latest API.
```diff
```diff
-const resolver = builtinResolvers.findAllComponentDefinitions
+const resolver = new builtinResolvers.FindAllDefinitionsResolver()
```
```
```diff
```diff
-const resolver = builtinResolvers.findAllExportedComponentDefinitions
+const resolver = new builtinResolvers.FindExportedDefinitionsResolver()
```
```
```diff
```diff
-const resolver = builtinResolvers.findExportedComponentDefinition
+const resolver = new builtinResolvers.FindExportedDefinitionsResolver({ limit: 1 })
```
```
--------------------------------
### Specify Handlers Multiple Times
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/cli/page.mdx
Use the --handler option multiple times to specify individual handlers for extracting component information.
```shell
react-docgen --handler handler1 --handler handler2
```
--------------------------------
### Instantiate FindExportedDefinitionsResolver
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/resolvers/find-exported-definitions-resolver/page.mdx
Instantiate the resolver with optional configuration. The `limit` option can be set to throw an error if more than one component definition is found.
```typescript
new FindExportedDefinitionsResolver({ limit?: number });
```
--------------------------------
### Chaining Multiple Resolvers CLI
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/cli/page.mdx
The `--resolver` option can now be used multiple times to chain resolvers. This allows for collecting components from different resolution strategies in a single run.
```bash
react-docgen --resolver first-resolver --resolver second-resolver
```
--------------------------------
### Using FindAnnotatedDefinitionsResolver
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/cli/page.mdx
Adds support for the `FindAnnotatedDefinitionsResolver`. This resolver can be used to find all annotated components.
```bash
react-docgen --resolver find-all-annotated-components
```
--------------------------------
### ChainResolver Constructor
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/resolvers/chain-resolver/page.mdx
Initializes a new ChainResolver with a list of resolvers and optional chaining logic.
```APIDOC
## new ChainResolver(resolvers, options)
### Description
Initializes a new ChainResolver instance.
### Parameters
#### resolvers
- **resolvers** (Resolver[]) - Required - An array of Resolver instances to be executed.
#### options
- **chainingLogic** (ChainResolver.Logic) - Optional - Controls how the results from multiple resolvers are combined. Defaults to `ChainResolver.Logic.ALL`.
- `ChainResolver.Logic.ALL`: Runs all resolvers and returns all unique components found.
- `ChainResolver.Logic.FIRST_FOUND`: Runs resolvers in order and returns the result from the first resolver that finds any components.
```
--------------------------------
### Specify Handlers with Comma-Separated List
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/cli/page.mdx
Use the --handler option with a comma-separated list to specify multiple handlers for extracting component information.
```shell
react-docgen --handler "handler1,handler2"
```
--------------------------------
### Instantiate ChainResolver
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/resolvers/chain-resolver/page.mdx
Create a new ChainResolver instance by providing an array of resolvers and an optional configuration object for chaining logic.
```typescript
new ChainResolver(resolvers, {
chainingLogic?: ChainResolver.Logic;
});
```
--------------------------------
### Output of defaultPropsHandler
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/default-props-handler/page.mdx
The resulting documentation structure when the defaultPropsHandler processes components with default props.
```json
[
{
"props": {
"a": {
"defaultValue": {
"value": "'1'",
"computed": false
},
"required": false
}
}
}
]
```
--------------------------------
### Updated parse() API Signature
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/migrate/v6/page.mdx
The parse method in v6 has a simplified signature with fewer arguments. The configuration object now consolidates several previous options.
```diff
-parse(src, resolver, handlers, importer, options: { filename, ...babelOptions})
+parse(src, { resolver, handlers, importer, filename, babelOptions: {} })
```
--------------------------------
### Specify Resolvers Multiple Times
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/cli/page.mdx
Use the --resolver option multiple times to specify individual resolvers for finding react components in the code.
```shell
react-docgen --resolver find-exported-component --resolver find-all-annotated-components
```
--------------------------------
### Migrate ast-types checks to Babel path methods
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/migrate/v6/page.mdx
Replace `ast-types` named type checks with Babel's `path.isType()` methods. Also, update how to access parent paths and iterate over node properties.
```diff
-import { namedTypes as types } from 'ast-types';
-if (types.FunctionExpression.check(path.node)) {}
+if (path.isFunctionExpression()) {}
-const leftPath = path.parent.get('left');
+const leftPath = path.parentPath.get('left');
-functionExpression.get('params').each(paramPath => {})
+functionExpression.get('params').forEach(paramPath => {})
-const first = functionExpression.get('params', 0)
+const first = functionExpression.get('params')[0]
```
--------------------------------
### Migrate handlers to use Babel path methods
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/migrate/v6/page.mdx
Update handlers to use Babel's `path.isType()` methods instead of `ast-types` for type checking nodes. The `NodePath` type is also updated to `builtinResolvers.ComponentNodePath`.
```diff
-import { namedTypes as types } from 'ast-types';
-import { NodePath } from 'ast-types/lib/node-path';
+import { Documentation, builtinResolvers } from 'react-docgen';
-export default function(documentation: Documentation, path: NodePath): void {
+export default function(documentation: Documentation, path: builtinResolvers.ComponentNodePath): void {
- if (types.FunctionExpression.check(path.node)) {
+ if (path.isFunctionExpression()) {
return;
}
}
```
--------------------------------
### CLI Option Renamed
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/cli/page.mdx
The `--handlers` option has been renamed to `--handler` to unify all options to be singular.
```bash
react-docgen --handler
```
--------------------------------
### Documentation Interface
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/documentation/basic/page.mdx
Defines the structure of the documentation object returned by react-docgen.
```typescript
interface Documentation {
childContext?: Record;
composes?: string[];
context?: Record;
description?: string;
displayName?: string;
methods?: MethodDescriptor[];
props?: Record;
}
```
--------------------------------
### Class Component with Static defaultProps
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/default-props-handler/page.mdx
Demonstrates how the defaultPropsHandler processes a class component with a static `defaultProps` property.
```typescript
class MyComponent extends React.Component {
static defaultProps = {
a: '1',
};
render() {
return ;
}
}
```
--------------------------------
### propDocblockHandler Output JSON
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/prop-docblock-handler/page.mdx
This JSON output represents the result of applying the propDocblockHandler to a component, showing extracted prop descriptions.
```json
[
{
"props": {
"foo": {
"description": "Foo"
},
"bar": {
"description": ""
}
}
}
]
```
--------------------------------
### Migrate resolvers to use FileState
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/migrate/v6/page.mdx
Update resolvers to accept a single `FileState` argument instead of multiple arguments like `ast`, `parser`, and `importer`. The `FileState` object provides access to parsing, traversal, and import functionalities.
```diff
-import { visit } from 'ast-types';
-import { NodePath } from 'ast-types/lib/node-path';
+import type { FileState } from 'react-docgen';
export default function (
- ast: FileNodeWithOptions,
+ file: FileState,
- parser: Parser,
- importer: Importer,
-): NodePath[] {}
+): builtinResolvers.ComponentNodePath[] {
- path = resolveToValue(path.get('right'), importer);
+ path = resolveToValue(path.get('right'));
- parser.parse('let x = 1');
+ file.parse('let x = 1', 'filename.tsx')
- visit(ast, {
+ file.traverse({
- visitFunctionDeclaration(path) {
+ FunctionDeclaration(path) {
// do not traverse into subpaths
- return false;
+ path.skip();
},
)
}
```
--------------------------------
### parse
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/api/page.mdx
Parses JavaScript, TypeScript, JSX, or TSX source code and returns documentation objects for each component found. The `filename` option is recommended for correct parser mode and relative import resolution.
```APIDOC
## parse
### Description
Parses JavaScript, TypeScript, JSX, or TSX source code and returns one documentation object for each component found by the configured resolver.
### Signature
```typescript
function parse(src: Buffer | string, config?: Config): Documentation[];
```
### Parameters
#### src
- `src` (Buffer | string) - The source code to parse.
#### config
- `config` (Config) - Optional configuration object.
- `filename` (string) - The name of the file being parsed. Recommended for TypeScript files and relative import resolution.
### Returns
- `Documentation[]` - An array of documentation objects, one for each component found.
```
--------------------------------
### Import Default Handlers
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/api/page.mdx
Import `defaultHandlers` which represents the list of handlers used when no `handlers` config option is specified.
```typescript
import { defaultHandlers } from 'react-docgen';
```
--------------------------------
### Renamed Resolver: findAllExportedComponentDefinitions
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/migrate/v6/page.mdx
The `findAllExportedComponentDefinitions` resolver is now a class and must be instantiated. Use `builtinResolvers` to access it.
```diff
-const resolver = builtinResolvers.findAllExportedComponentDefinitions
+const resolver = new builtinResolvers.FindExportedDefinitionsResolver()
```
--------------------------------
### Specify Resolvers with Comma-Separated List
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/cli/page.mdx
Use the --resolver option with a comma-separated list to specify multiple resolvers for finding react components in the code.
```shell
react-docgen --resolver "find-exported-component,find-all-annotated-components"
```
--------------------------------
### Class Component with Assigned defaultProps
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/default-props-handler/page.mdx
Shows how the handler works with a class component where `defaultProps` is assigned after the component definition.
```typescript
class MyComponent extends React.Component {
render() {
return ;
}
}
MyComponent.defaultProps = {
a: '1',
};
```
--------------------------------
### Annotate Components for Resolution
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/react-docgen/page.mdx
Illustrates how to use the `@component` annotation to explicitly mark components for resolution by the default resolver.
```typescript
// @component
class MyComponent {}
```
--------------------------------
### Output JSON from Docblock Handler
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/component-docblock-handler/page.mdx
This JSON output represents the documentation generated after the componentDocblockHandler processes the component's docblock.
```json
[
{
"description": "This is my component and this is its description."
}
]
```
--------------------------------
### Functional Component Prop Types with Docblock
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/prop-docblock-handler/page.mdx
Illustrates how propDocblockHandler handles a functional React component with propTypes defined separately and including JSDoc comments.
```typescript
import PropTypes from 'prop-types';
const MyComponent = () => ;
MyComponent.propTypes = {
/** Foo */
foo: PropTypes.string,
bar: PropTypes.number,
};
```
--------------------------------
### Function Component Method as Static Property
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/component-methods-handler/page.mdx
Illustrates the detection of methods assigned as static properties to a function component. This allows functional components to expose imperative methods similarly to class components.
```typescript
const MyComponent = () => ;
/** myMethod description */
MyComponent.myMethod = (argument: string): number => {};
```
--------------------------------
### Define a custom Handler
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/extending/handler/page.mdx
A custom handler receives a `DocumentationBuilder` and the Babel `NodePath` for the component definition. Use `documentation.set()` to add custom values.
```typescript
import type { Handler } from 'react-docgen';
const handler: Handler = (documentation, componentDefinition) => {
documentation.set('customValue', componentDefinition.node.type);
};
```
--------------------------------
### Config Interface Definition
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/config/page.mdx
Defines the structure of the configuration object used by react-docgen.
```typescript
interface Config {
handlers?: Handler[];
importer?: Importer;
resolver?: Resolver;
filename?: string;
babelOptions?: TransformOptions;
}
```
--------------------------------
### Function Component with Assigned defaultProps
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/default-props-handler/page.mdx
Illustrates the defaultPropsHandler's behavior with a function component that has `defaultProps` assigned.
```typescript
const MyComponent = () => ;
MyComponent.defaultProps = {
a: '1',
};
```
--------------------------------
### PropDescriptor Interface
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/documentation/basic/page.mdx
Defines the structure for individual prop descriptors, including type, requirement, default value, and description.
```typescript
interface PropDescriptor {
type?: PropTypeDescriptor;
flowType?: TypeDescriptor;
tsType?: TypeDescriptor;
required?: boolean;
defaultValue?: DefaultValueDescriptor;
description?: string;
}
```
--------------------------------
### Class Component with PropTypes Defined After Declaration
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/prop-type-composition-handler/page.mdx
Demonstrates a class component where propTypes are assigned after the component's initial declaration. The handler processes this assignment to identify composed types.
```typescript
import otherPropTypes from './Link.js';
import { Component } from 'react';
class Button extends Component {
render() {
return ;
}
}
Button.propTypes = {
...otherPropTypes,
};
```
--------------------------------
### Output of childContextTypeHandler
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/child-context-type-handler/page.mdx
The expected JSON output structure documenting the child context types, including type and required status.
```json
[
{
"childContext": {
"theme": {
"type": {
"name": "string"
},
"required": false
},
"disabled": {
"type": {
"name": "bool"
},
"required": true
}
}
}
]
```
--------------------------------
### Class Component Method as Static Property
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/component-methods-handler/page.mdx
Shows how the handler identifies methods assigned as static properties to a class component after its definition. This is useful for organizing methods separately.
```typescript
class MyComponent extends React.Component {
render() {
return ;
}
}
/** myMethod description */
MyComponent.myMethod = (argument: string): number => {};
```
--------------------------------
### Import Built-in Importers
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/api/page.mdx
Import `builtinImporters` to access the file system (`fsImporter`) and ignore (`ignoreImporter`) importers.
```typescript
import { builtinImporters } from 'react-docgen';
```
--------------------------------
### Unified Singular Handler Option CLI
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/cli/page.mdx
This change unified the `--handlers` option to `--handler` for consistency. Use the singular form when specifying handlers.
```bash
react-docgen --handler some-handler
```
--------------------------------
### Import Built-in Resolvers
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/api/page.mdx
Import `builtinResolvers` to access resolver classes like `ChainResolver`, `FindAllDefinitionsResolver`, `FindAnnotatedDefinitionsResolver`, and `FindExportedDefinitionsResolver`.
```typescript
import { builtinResolvers } from 'react-docgen';
```
--------------------------------
### builtinHandlers
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/api/page.mdx
Contains all built-in handlers keyed by their export name. These handlers can be passed to `parse()` with the `handlers` config option.
```APIDOC
## builtinHandlers
### Description
Contains all built-in handlers keyed by their export name. These handlers can be passed to `parse()` with the `handlers` config option.
### Usage
```typescript
import { builtinHandlers } from 'react-docgen';
```
```
--------------------------------
### Handler Output for Composed Prop Types
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/prop-type-composition-handler/page.mdx
The expected JSON output when the propTypeCompositionHandler is active and identifies composed prop types from an unresolvable import.
```json
[
{
"composes": ["./Link.js"]
}
]
```
--------------------------------
### JSON Output of Component Methods
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/component-methods-handler/page.mdx
This JSON structure represents the output generated by the componentMethodsHandler, detailing the name, documentation, modifiers, parameters, and return types of identified methods.
```json
[
{
"methods": [
{
"name": "myMethod",
"docblock": "myMethod description",
"modifiers": ["static"],
"params": [
{
"name": "argument",
"optional": false,
"type": {
"name": "string"
}
}
],
"returns": {
"type": {
"name": "number"
}
}
}
]
}
]
```
--------------------------------
### Update resolveToValue for Import Specifier Resolution
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/react-docgen/page.mdx
Shows a code snippet demonstrating the updated behavior of `resolveToValue`. It now resolves to specific import specifiers instead of the entire `ImportDeclaration`, requiring a check on the parent path.
```diff
const resolved = resolveToValue(path);
-if (resolved.isImportDeclaration()) {
+if (resolved.parentPath?.isImportDeclaration()) {
// do smth
}
```
--------------------------------
### Using a Custom Resolver with react-docgen
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/extending/resolver/page.mdx
Integrate a custom resolver into the `parse` function by passing it as an option. Ensure the resolver is correctly imported.
```typescript
import { parse } from 'react-docgen';
import myResolver from './myResolver.js';
const docs = parse(code, {
filename: 'Button.tsx',
resolver: myResolver,
});
```
--------------------------------
### Support Generic Types on React.forwardRef
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/react-docgen/page.mdx
Demonstrates how react-docgen now correctly identifies generic types, such as IButtonProps, when used with React.forwardRef. This change improves type inference for components created with forwardRef.
```typescript
export const FullWidthButton = forwardRef(
() => {},
);
```
--------------------------------
### builtinImporters
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/api/page.mdx
Contains the built-in importers: `fsImporter` and `ignoreImporter`.
```APIDOC
## builtinImporters
### Description
Contains the built-in importers:
- `fsImporter`
- `ignoreImporter`
### Usage
```typescript
import { builtinImporters } from 'react-docgen';
```
```
--------------------------------
### PropDescriptor Interface
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/documentation/flow/page.mdx
Defines the structure for describing component properties when using Flow. It includes optional flow type information, requirement status, description, and default value.
```typescript
interface PropDescriptor {
flowType?: TypeDescriptor;
required?: boolean;
description?: string;
defaultValue?: DefaultValueDescriptor;
}
```
--------------------------------
### Resolver Function Signature
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/extending/resolver/page.mdx
A resolver can be implemented as a function that accepts a `FileState` object and returns an array of `NodePath`.
```typescript
import type { ResolverFunction } from 'react-docgen';
const resolver: ResolverFunction = (file) => {
return [];
};
```
--------------------------------
### Updated parse API Signature
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/release-notes/react-docgen/page.mdx
The main parse API has been updated to accept only two arguments. The second argument is now an object containing resolver, handlers, importer, and other options.
```diff
-parse(src, resolver, handlers, importer, options)
+parse(src, { resolver, handlers, importer, ... })
```
--------------------------------
### Class Component with Static propTypes
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/prop-type-handler/page.mdx
This snippet demonstrates how the propTypeHandler identifies prop types defined as a static property on a React class component. Ensure PropTypes are imported.
```typescript
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
static propTypes = {
foo: PropTypes.string,
bar: PropTypes.number.isRequired,
};
render() {
return ;
}
}
```
--------------------------------
### Instantiate FindAnnotatedDefinitionsResolver with custom annotation
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/resolvers/find-annotated-definitions-resolver/page.mdx
Instantiate the resolver with a custom annotation string to search for in leading comments.
```typescript
new FindAnnotatedDefinitionsResolver({ annotation?: string });
```
--------------------------------
### Class Component Static Method
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/handlers/component-methods-handler/page.mdx
Demonstrates how the componentMethodsHandler detects static methods defined directly within a class component. Ensure the method has a JSDoc comment for documentation.
```typescript
class MyComponent extends React.Component {
/** myMethod description */
static myMethod(argument: string): number {}
render() {
return ;
}
}
```
--------------------------------
### Removed Resolver: findExportedComponentDefinition
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/migrate/v6/page.mdx
The `findExportedComponentDefinition` resolver has been removed. Use `FindExportedDefinitionsResolver` with the `limit` option set to 1.
```diff
-const resolver = builtinResolvers.findExportedComponentDefinition
+const resolver = new builtinResolvers.FindExportedDefinitionsResolver({ limit: 1 })
```
--------------------------------
### Customizing Handlers
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/config/page.mdx
Specify a custom array of handlers to extract information from components. If not provided, all built-in handlers are used.
```typescript
import { builtinHandlers, parse } from 'react-docgen';
parse(code, {
handlers: [builtinHandlers.componentDocblockHandler],
});
```
--------------------------------
### Parse Source Code
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/reference/api/page.mdx
Use the `parse` function to process JavaScript, TypeScript, JSX, or TSX source code. The `filename` option is recommended for correct parser mode and relative import resolution.
```typescript
function parse(src: Buffer | string, config?: Config): Documentation[];
```
```typescript
import { parse } from 'react-docgen';
const docs = parse(
`
/** Button component */
export function Button({ label }: { label: string }) {
return ;
}
`,
{ filename: 'Button.tsx' },
);
```
--------------------------------
### Parse React component code in Node.js
Source: https://github.com/reactjs/react-docgen/blob/main/packages/website/src/app/docs/getting-started/nodejs/page.mdx
Use the parse function from react-docgen to extract documentation from a React component's code string. The filename option is recommended for accurate parsing.
```typescript
import { parse } from 'react-docgen';
const code = `
/** My first component */
export default ({ name }: { name: string }) =>