0
# Import/Export Analysis
1
2
Fast regex-based static analysis for finding and parsing ECMAScript import and export statements. Supports static imports, dynamic imports, type imports, and all export patterns without requiring full AST parsing.
3
4
## Capabilities
5
6
### Find Static Imports
7
8
Finds all static import statements within the given code string.
9
10
```typescript { .api }
11
/**
12
* Finds all static import statements within the given code string
13
* @param code - The source code to search for static imports
14
* @returns An array of StaticImport objects representing each static import found
15
*/
16
function findStaticImports(code: string): StaticImport[];
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { findStaticImports } from "mlly";
23
24
const code = `
25
import foo, { bar } from './module.mjs';
26
import { baz as qux } from 'package';
27
`;
28
29
const imports = findStaticImports(code);
30
console.log(imports[0].specifier); // "./module.mjs"
31
console.log(imports[0].imports); // "foo, { bar } "
32
```
33
34
### Find Dynamic Imports
35
36
Searches for dynamic import statements in the given source code.
37
38
```typescript { .api }
39
/**
40
* Searches for dynamic import statements in the given source code
41
* @param code - The source to search for dynamic imports in
42
* @returns An array of DynamicImport objects representing each dynamic import found
43
*/
44
function findDynamicImports(code: string): DynamicImport[];
45
```
46
47
**Usage Examples:**
48
49
```typescript
50
import { findDynamicImports } from "mlly";
51
52
const code = `
53
const module = await import('./module.mjs');
54
import('./conditional.mjs').then(m => m.default());
55
`;
56
57
const dynamicImports = findDynamicImports(code);
58
console.log(dynamicImports[0].expression); // "'./module.mjs'"
59
```
60
61
### Find Type Imports
62
63
Identifies and returns all type import statements in the given source code. This function is specifically targeted at type imports used in TypeScript.
64
65
```typescript { .api }
66
/**
67
* Identifies and returns all type import statements in the given source code
68
* @param code - The source code to search for type imports
69
* @returns An array of TypeImport objects representing each type import found
70
*/
71
function findTypeImports(code: string): TypeImport[];
72
```
73
74
**Usage Examples:**
75
76
```typescript
77
import { findTypeImports } from "mlly";
78
79
const code = `
80
import type { User, Config } from './types';
81
import { type Database, connect } from './database';
82
`;
83
84
const typeImports = findTypeImports(code);
85
console.log(typeImports[0].specifier); // "./types"
86
console.log(typeImports[0].imports); // " User, Config "
87
```
88
89
### Parse Static Import
90
91
Parses a static import or type import to extract detailed import elements such as default, namespace and named imports.
92
93
```typescript { .api }
94
/**
95
* Parses a static import or type import to extract detailed import elements such as default, namespace and named imports
96
* @param matched - The matched import statement to parse
97
* @returns A structured object representing the parsed static import
98
*/
99
function parseStaticImport(matched: StaticImport | TypeImport): ParsedStaticImport;
100
```
101
102
**Usage Example:**
103
104
```typescript
105
import { findStaticImports, parseStaticImport } from "mlly";
106
107
const [match] = findStaticImports(`import foo, { bar as baz } from 'module'`);
108
const parsed = parseStaticImport(match);
109
110
console.log(parsed.defaultImport); // "foo"
111
console.log(parsed.namedImports); // { bar: "baz" }
112
```
113
114
### Parse Type Import
115
116
Parses a static import or type import to extract detailed import elements such as default, namespace and named imports, specifically for TypeScript type imports.
117
118
```typescript { .api }
119
/**
120
* Parses a static import or type import to extract detailed import elements such as default, namespace and named imports
121
* @param matched - The matched import statement to parse
122
* @returns A structured object representing the parsed static import
123
*/
124
function parseTypeImport(matched: TypeImport | StaticImport): ParsedStaticImport;
125
```
126
127
**Usage Example:**
128
129
```typescript
130
import { findTypeImports, parseTypeImport } from "mlly";
131
132
const [typeMatch] = findTypeImports(`import type { User as UserType, Config } from 'types'`);
133
const parsed = parseTypeImport(typeMatch);
134
135
console.log(parsed.namedImports); // { User: "UserType", Config: "Config" }
136
```
137
138
### Find Exports
139
140
Identifies all export statements in the supplied source code and categorises them into different types such as declarations, named, default and star exports.
141
142
```typescript { .api }
143
/**
144
* Identifies all export statements in the supplied source code and categorises them into different types such as declarations, named, default and star exports
145
* @param code - The source code containing the export statements to be analysed
146
* @returns An array of ESMExport objects representing each export found, properly categorised and structured
147
*/
148
function findExports(code: string): ESMExport[];
149
```
150
151
**Usage Examples:**
152
153
```typescript
154
import { findExports } from "mlly";
155
156
const code = `
157
export const foo = 'bar';
158
export { baz, qux as quux };
159
export default class MyClass {}
160
export * from './other.mjs';
161
`;
162
163
const exports = findExports(code);
164
// Returns exports categorized by type: declaration, named, default, star
165
```
166
167
### Find Type Exports
168
169
Searches specifically for type-related exports in TypeScript code, such as exported interfaces, types, and declarations prefixed with 'declare'.
170
171
```typescript { .api }
172
/**
173
* Searches specifically for type-related exports in TypeScript code, such as exported interfaces, types, and declarations prefixed with 'declare'
174
* @param code - The TypeScript source code to search for type exports
175
* @returns An array of ESMExport objects representing each type export found
176
*/
177
function findTypeExports(code: string): ESMExport[];
178
```
179
180
### Find Export Names
181
182
Extracts and returns a list of all export names from the given source.
183
184
```typescript { .api }
185
/**
186
* Extracts and returns a list of all export names from the given source
187
* @param code - The source code to search for export names
188
* @returns An array containing the names of all exports found in the code
189
*/
190
function findExportNames(code: string): string[];
191
```
192
193
### Resolve Module Export Names
194
195
Asynchronously resolves and returns all export names from a module specified by its module identifier.
196
197
```typescript { .api }
198
/**
199
* Asynchronously resolves and returns all export names from a module specified by its module identifier
200
* @param id - The module identifier to resolve
201
* @param options - Optional settings for resolving the module path, such as the base URL
202
* @returns A promise that resolves to an array of export names from the module
203
*/
204
function resolveModuleExportNames(id: string, options?: ResolveOptions): Promise<string[]>;
205
```
206
207
**Usage Example:**
208
209
```typescript
210
import { resolveModuleExportNames } from "mlly";
211
212
// Get all export names from a package
213
const exports = await resolveModuleExportNames("lodash");
214
console.log(exports); // ["map", "filter", "reduce", ...]
215
```
216
217
## Regular Expressions
218
219
mlly exports several useful regular expressions for parsing import and export statements:
220
221
```typescript { .api }
222
/** Regular expression to match static import statements in JavaScript/TypeScript code */
223
const ESM_STATIC_IMPORT_RE: RegExp;
224
225
/** Regular expression to match dynamic import statements in JavaScript/TypeScript code */
226
const DYNAMIC_IMPORT_RE: RegExp;
227
228
/** Regular expression to match various types of export declarations including variables, functions, and classes */
229
const EXPORT_DECAL_RE: RegExp;
230
231
/** Regular expression to match export declarations specifically for types, interfaces, and type aliases in TypeScript */
232
const EXPORT_DECAL_TYPE_RE: RegExp;
233
```
234
235
**Usage Example:**
236
237
```typescript
238
import { ESM_STATIC_IMPORT_RE, DYNAMIC_IMPORT_RE } from "mlly";
239
240
// Use regex directly for custom parsing
241
const code = `import { foo } from "bar"; const x = import("dynamic");`;
242
const staticMatches = [...code.matchAll(ESM_STATIC_IMPORT_RE)];
243
const dynamicMatches = [...code.matchAll(DYNAMIC_IMPORT_RE)];
244
```
245
246
## Types
247
248
```typescript { .api }
249
interface ESMImport {
250
/** Specifies the type of import: "static" for static imports and "dynamic" for dynamic imports */
251
type: "static" | "dynamic";
252
/** The full import declaration code snippet as a string */
253
code: string;
254
/** The starting position (index) of the import declaration in the source code */
255
start: number;
256
/** The end position (index) of the import declaration in the source code */
257
end: number;
258
}
259
260
interface StaticImport extends ESMImport {
261
/** Indicates the type of import, specifically a static import */
262
type: "static";
263
/** Contains the entire import statement as a string, excluding the module specifier */
264
imports: string;
265
/** The module specifier from which imports are being brought in */
266
specifier: string;
267
}
268
269
interface ParsedStaticImport extends StaticImport {
270
/** The default import name, if any */
271
defaultImport?: string;
272
/** The namespace import name, if any, using the `* as` syntax */
273
namespacedImport?: string;
274
/** An object representing named imports, with their local aliases if specified */
275
namedImports?: { [name: string]: string };
276
}
277
278
interface DynamicImport extends ESMImport {
279
/** Indicates that this is a dynamic import */
280
type: "dynamic";
281
/** The expression or path to be dynamically imported, typically a module path or URL */
282
expression: string;
283
}
284
285
interface TypeImport extends Omit<ESMImport, "type"> {
286
/** Specifies that this is a type import */
287
type: "type";
288
/** Contains the entire type import statement as a string, excluding the module specifier */
289
imports: string;
290
/** The module specifier from which to import types */
291
specifier: string;
292
}
293
294
interface ESMExport {
295
/** The type of export (declaration, named, default or star) */
296
type: "declaration" | "named" | "default" | "star";
297
/** The specific type of declaration being exported, if applicable */
298
declarationType?: "let" | "var" | "const" | "enum" | "const enum" | "class" | "function" | "async function";
299
/** The full code snippet of the export statement */
300
code: string;
301
/** The starting position (index) of the export declaration in the source code */
302
start: number;
303
/** The end position (index) of the export declaration in the source code */
304
end: number;
305
/** The name of the variable, function or class being exported, if given explicitly */
306
name?: string;
307
/** The name used for default exports when a specific identifier isn't given */
308
defaultName?: string;
309
/** An array of names to export, applicable to named and destructured exports */
310
names: string[];
311
/** The module specifier, if any, from which exports are being re-exported */
312
specifier?: string;
313
}
314
315
interface DeclarationExport extends ESMExport {
316
/** Indicates that this export is a declaration export */
317
type: "declaration";
318
/** The declaration string, such as 'let', 'const', 'class', etc., describing what is being exported */
319
declaration: string;
320
/** The name of the declaration to be exported */
321
name: string;
322
}
323
324
interface NamedExport extends ESMExport {
325
/** Specifies that this export is a named export */
326
type: "named";
327
/** The export string, containing all exported identifiers */
328
exports: string;
329
/** An array of names to export */
330
names: string[];
331
/** The module specifier, if any, from which exports are being re-exported */
332
specifier?: string;
333
}
334
335
interface DefaultExport extends ESMExport {
336
/** Specifies that this export is a standard export */
337
type: "default";
338
}
339
```