A library to extract information from React components for documentation generation.
npx @tessl/cli install tessl/npm-react-docgen@8.0.00
# React-docgen
1
2
React-docgen is a comprehensive library designed to extract structured metadata from React components for documentation generation. It analyzes React component source code using Babel parsing and AST traversal to automatically discover component properties, methods, type information, and JSDoc comments.
3
4
## Package Information
5
6
- **Package Name**: react-docgen
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install react-docgen`
10
11
## Core Imports
12
13
```typescript
14
import { parse } from "react-docgen";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { parse } = require("react-docgen");
21
```
22
23
Additional imports for advanced usage:
24
25
```typescript
26
import {
27
parse,
28
builtinHandlers,
29
builtinResolvers,
30
builtinImporters,
31
utils,
32
ERROR_CODES,
33
makeFsImporter
34
} from "react-docgen";
35
36
// Type imports
37
import type {
38
Documentation,
39
DocumentationBuilder,
40
Config,
41
Handler,
42
Resolver,
43
Importer,
44
FileState,
45
NodePath,
46
babelTypes
47
} from "react-docgen";
48
```
49
50
## Basic Usage
51
52
```typescript
53
import { parse } from "react-docgen";
54
55
// Parse a React component
56
const componentCode = `
57
import React from 'react';
58
59
interface Props {
60
/** The name to display */
61
name: string;
62
/** Whether the component is active */
63
active?: boolean;
64
}
65
66
/**
67
* A greeting component that displays a name
68
*/
69
export default function Greeting({ name, active = false }: Props) {
70
return <div className={active ? 'active' : ''}>{name}</div>;
71
}
72
`;
73
74
const docs = parse(componentCode);
75
console.log(docs);
76
// Returns array of Documentation objects with props, methods, description, etc.
77
```
78
79
## Architecture
80
81
React-docgen is built around several key components:
82
83
- **Parser Core**: Main parsing function that orchestrates the analysis process
84
- **Resolver System**: Finds and identifies React component definitions in source code
85
- **Handler System**: Extracts specific information from components (props, methods, JSDoc, etc.)
86
- **Importer System**: Resolves module imports and dependencies during analysis
87
- **Documentation Builder**: Constructs structured documentation objects from extracted data
88
- **Type Analysis**: Comprehensive TypeScript and Flow type extraction utilities
89
90
## Capabilities
91
92
### Core Parsing
93
94
Main parsing functionality for extracting React component documentation from source code.
95
96
```typescript { .api }
97
function parse(src: Buffer | string, config?: Config): Documentation[];
98
99
interface Documentation {
100
childContext?: Record<string, PropDescriptor>;
101
composes?: string[];
102
context?: Record<string, PropDescriptor>;
103
description?: string;
104
displayName?: string;
105
methods?: MethodDescriptor[];
106
props?: Record<string, PropDescriptor>;
107
}
108
109
class DocumentationBuilder {
110
constructor();
111
addComposes(moduleName: string): void;
112
set(key: string, value: unknown): void;
113
get<T>(key: string): T | null;
114
getPropDescriptor(propName: string): PropDescriptor;
115
getContextDescriptor(propName: string): PropDescriptor;
116
getChildContextDescriptor(propName: string): PropDescriptor;
117
build(): Documentation;
118
}
119
```
120
121
[Core Parsing](./parsing.md)
122
123
### Component Resolution
124
125
System for finding and identifying React component definitions within source files.
126
127
```typescript { .api }
128
interface FindExportedDefinitionsResolver {
129
resolve: (file: FileState) => ComponentNodePath[];
130
}
131
132
interface FindAllDefinitionsResolver {
133
resolve: (file: FileState) => ComponentNodePath[];
134
}
135
136
interface FindAnnotatedDefinitionsResolver {
137
resolve: (file: FileState) => ComponentNodePath[];
138
}
139
```
140
141
[Component Resolution](./resolvers.md)
142
143
### Information Extraction
144
145
Handlers that extract specific types of information from React components.
146
147
```typescript { .api }
148
type Handler = (
149
documentation: Documentation,
150
componentDefinition: NodePath<ComponentNode>
151
) => void;
152
```
153
154
[Information Extraction](./handlers.md)
155
156
### Module Import Resolution
157
158
System for resolving module imports and dependencies during component analysis.
159
160
```typescript { .api }
161
type Importer = (
162
path: ImportPath,
163
name: string,
164
file: FileState
165
) => NodePath | null;
166
```
167
168
[Module Import Resolution](./importers.md)
169
170
### Configuration
171
172
Configuration system for customizing parsing behavior and analysis options.
173
174
```typescript { .api }
175
interface Config {
176
handlers?: Handler[];
177
importer?: Importer;
178
resolver?: Resolver;
179
filename?: string;
180
babelOptions?: TransformOptions;
181
}
182
```
183
184
[Configuration](./configuration.md)
185
186
### AST Analysis Utilities
187
188
Comprehensive collection of utilities for React component and TypeScript/Flow analysis.
189
190
```typescript { .api }
191
// Key utility namespaces
192
namespace utils {
193
namespace docblock;
194
namespace expressionTo;
195
namespace flowUtilityTypes;
196
namespace traverse;
197
}
198
```
199
200
[AST Analysis Utilities](./utilities.md)
201
202
### Error Handling
203
204
Error handling system for parsing failures and validation issues.
205
206
```typescript { .api }
207
enum ERROR_CODES {
208
MISSING_DEFINITION = 'ERR_REACTDOCGEN_MISSING_DEFINITION',
209
MULTIPLE_DEFINITIONS = 'ERR_REACTDOCGEN_MULTIPLE_DEFINITIONS',
210
}
211
```
212
213
[Error Handling](./error-handling.md)
214
215
## Types
216
217
```typescript { .api }
218
interface PropDescriptor {
219
type?: PropTypeDescriptor;
220
flowType?: TypeDescriptor<FunctionSignatureType>;
221
tsType?: TypeDescriptor<TSFunctionSignatureType>;
222
required?: boolean;
223
defaultValue?: DefaultValueDescriptor;
224
description?: string;
225
}
226
227
interface MethodDescriptor {
228
name: string;
229
description?: string | null;
230
docblock: string | null;
231
modifiers: MethodModifier[];
232
params: MethodParameter[];
233
returns: MethodReturn | null;
234
}
235
236
interface MethodParameter {
237
name: string;
238
description?: string;
239
optional: boolean;
240
type?: TypeDescriptor<FunctionSignatureType> | null;
241
}
242
243
type ComponentNode =
244
| CallExpression
245
| ClassDeclaration
246
| ClassExpression
247
| ObjectExpression
248
| StatelessComponentNode;
249
250
type StatelessComponentNode =
251
| ArrowFunctionExpression
252
| FunctionDeclaration
253
| FunctionExpression
254
| ObjectMethod;
255
256
// Type aliases and interfaces
257
interface FileState {
258
// Internal file state used by parsers and importers
259
}
260
261
type InternalConfig = Omit<Required<Config>, 'filename'>;
262
263
// Re-exported from Babel for convenience
264
type NodePath = import('@babel/traverse').NodePath;
265
type babelTypes = typeof import('@babel/types');
266
```