0
# Module Import Resolution
1
2
System for resolving module imports and dependencies during component analysis, enabling cross-file component discovery.
3
4
## Capabilities
5
6
### Importer Interface
7
8
The base interface for all module import resolvers.
9
10
```typescript { .api }
11
type Importer = (
12
path: ImportPath,
13
name: string,
14
file: FileState
15
) => NodePath | null;
16
17
type ImportPath = NodePath<
18
ExportAllDeclaration | ExportNamedDeclaration | ImportDeclaration
19
>;
20
```
21
22
**Parameters:**
23
- `path`: AST path of the import/export statement
24
- `name`: The identifier being imported/exported
25
- `file`: Current file state with parsing context
26
27
**Returns:**
28
- `NodePath`: Resolved AST node if found
29
- `null`: If import cannot be resolved
30
31
### Filesystem Importer
32
33
Resolves imports using Node.js filesystem resolution algorithm.
34
35
```typescript { .api }
36
const fsImporter: Importer;
37
```
38
39
**Resolution Algorithm:**
40
- Uses Node.js `require.resolve()` logic
41
- Supports npm package resolution
42
- Handles relative and absolute paths
43
- Resolves file extensions (.js, .ts, .jsx, .tsx)
44
- Follows package.json main/exports fields
45
46
**Usage Example:**
47
48
```typescript
49
import { parse, fsImporter } from "react-docgen";
50
51
// Component with imports
52
const componentCode = `
53
import { Button } from './Button';
54
import { theme } from '../theme';
55
56
export default function App() {
57
return <Button theme={theme} />;
58
}
59
`;
60
61
const docs = parse(componentCode, {
62
importer: fsImporter,
63
filename: '/path/to/App.jsx'
64
});
65
```
66
67
### Ignore Importer
68
69
Ignores all import resolution, useful for browser environments or when imports are not available.
70
71
```typescript { .api }
72
const ignoreImporter: Importer;
73
```
74
75
**Use Cases:**
76
- Browser environments without filesystem access
77
- Static analysis without dependency resolution
78
- Parsing isolated components
79
- Performance optimization when imports are not needed
80
81
**Usage Example:**
82
83
```typescript
84
import { parse, ignoreImporter } from "react-docgen";
85
86
// Parse without resolving imports
87
const docs = parse(componentCode, {
88
importer: ignoreImporter
89
});
90
```
91
92
### Filesystem Importer Factory
93
94
Creates customized filesystem importers with specific resolution options.
95
96
```typescript { .api }
97
function makeFsImporter(options?: FsImporterOptions): Importer;
98
99
interface FsImporterOptions {
100
/** Custom resolve function */
101
resolve?: (id: string, basedir: string) => string;
102
/** File extensions to resolve */
103
extensions?: string[];
104
/** Whether to follow symlinks */
105
preserveSymlinks?: boolean;
106
}
107
```
108
109
**Usage Example:**
110
111
```typescript
112
import { makeFsImporter, parse } from "react-docgen";
113
114
const customImporter = makeFsImporter({
115
extensions: ['.tsx', '.ts', '.jsx', '.js'],
116
preserveSymlinks: false
117
});
118
119
const docs = parse(componentCode, {
120
importer: customImporter,
121
filename: '/path/to/component.tsx'
122
});
123
```
124
125
### Browser Field Support
126
127
React-docgen automatically handles browser field mappings in package.json for browser compatibility.
128
129
```typescript { .api }
130
// Automatic browser field mappings:
131
const browserMappings = {
132
"./dist/importer/fsImporter.js": "./dist/importer/ignoreImporter.js",
133
"./src/importer/fsImporter.ts": "./src/importer/ignoreImporter.ts",
134
"./dist/importer/makeFsImporter.js": "./dist/importer/makeIgnoreImporter.js",
135
"./src/importer/makeFsImporter.ts": "./src/importer/makeIgnoreImporter.ts"
136
};
137
```
138
139
When used in browser environments, filesystem-based importers are automatically replaced with ignore-based importers.
140
141
### Import Resolution Process
142
143
The import resolution process follows these steps:
144
145
1. **Parse Import Statement**: Extract module specifier and imported names
146
2. **Resolve Module Path**: Use importer to find the target file
147
3. **Parse Target File**: Load and parse the resolved file
148
4. **Extract Exports**: Find the requested export in the target file
149
5. **Return AST Node**: Provide the resolved AST node for analysis
150
151
**Supported Import/Export Patterns:**
152
153
```typescript
154
// Named imports
155
import { Component } from './Component';
156
import { Component as MyComponent } from './Component';
157
158
// Default imports
159
import Component from './Component';
160
161
// Namespace imports
162
import * as Components from './Components';
163
164
// Named exports
165
export { Component };
166
export { Component as Button };
167
168
// Default exports
169
export default Component;
170
171
// Re-exports
172
export { Component } from './Component';
173
export * from './Components';
174
```
175
176
### Custom Importer Development
177
178
Importers can be customized for specific resolution strategies or environments.
179
180
**Custom Importer Example:**
181
182
```typescript
183
import type { Importer } from "react-docgen";
184
185
const customImporter: Importer = (path, name, file) => {
186
// Custom resolution logic
187
const modulePath = path.node.source?.value;
188
189
if (modulePath?.startsWith('@components/')) {
190
// Handle component library imports
191
return resolveComponentLibrary(modulePath, name);
192
}
193
194
if (modulePath?.startsWith('http://')) {
195
// Handle remote imports (not recommended for production)
196
return resolveRemoteModule(modulePath, name);
197
}
198
199
// Fallback to default resolution
200
return null;
201
};
202
203
// Usage with custom importer
204
const docs = parse(sourceCode, {
205
importer: customImporter
206
});
207
```
208
209
### Default Importer Configuration
210
211
The default importer used when no custom importer is specified.
212
213
```typescript { .api }
214
const defaultImporter: Importer;
215
```
216
217
The default configuration uses `fsImporter` with standard Node.js resolution for most environments, with automatic browser field mapping support.
218
219
### Error Handling
220
221
Import resolution errors are handled gracefully:
222
223
- **Module Not Found**: Returns `null`, allowing parsing to continue
224
- **Parse Errors**: Logged and ignored, doesn't break main parsing
225
- **Circular Dependencies**: Detected and handled to prevent infinite loops
226
- **Permission Errors**: Handled gracefully in restricted environments
227
228
**Error Handling Example:**
229
230
```typescript
231
import { parse } from "react-docgen";
232
233
const componentWithMissingImport = `
234
import { MissingComponent } from './does-not-exist';
235
236
export default function App() {
237
return <MissingComponent />;
238
}
239
`;
240
241
// Parsing continues even with unresolvable imports
242
const docs = parse(componentWithMissingImport);
243
// docs will contain available information, missing imports are ignored
244
```