Fast and easy parser for declarations of import
and export from the ECMAScript standard,
with TypeScript syntax support.
parse-imports-exports works for syntactically correct, well-formatted code (for example, by prettier).
Single-line and multi-line ECMAScript comments in import/export statements are supported.
Basic example
Imagine a module with the following content:
/** * Imports. */// {Qux: [{start: 17, end: 58, names: {baz: {by: 'foo'}}, types: {Bar: {}}}]}import {foo as baz, type Bar} from 'Qux';// {Qux: [{start: 80, end: 112, namespace: 'foo', default: 'Foo'}]}import Foo, * as foo from 'Qux';// {Qux: [{start: 114, end: 127}]}const foo = await import('Qux');// {Qux: [{start: 128, end, 134}]}const foo = require('Qux');// {Qux: [{start: 142, end: 175, names: {Baz: {by: 'Foo'}, Bar: {}}}]}import type {Foo as Baz, Bar} from 'Qux';// {Qux: [{start: 201, end: 233, namespace: 'Foo'}]}
Let its content be stored as a string in the variable source.
Then it can be parsed like this:
import {parseImportsExports} from 'parse-imports-exports';const importsExports = parseImportsExports(source);// Now `importsExports` has the following shape (the `start` and `end` indices, which indicate// the beginning and end of the corresponding statement in the source, may differ):const importsExportsShape = { /** * Imports. */ // import {foo as baz, type Bar} from 'Qux'; namedImports: {Qux: [{start: 17, end: 58, names: {baz: {by: 'foo'}}, types: {Bar: {}}}]}, // import Foo, * as foo from 'Qux'; namespaceImports: {Qux: [{start: 80, end: 112, namespace: 'foo', default: 'Foo'}]}, // const foo = await import('Qux'); dynamicImports: {Qux: [{start: 114, end: 127}]},
parse-imports-exports works in any environment that supports ES2018
(because package uses RegExp Named Capture Groups).
API
parse-imports-exports exports one runtime value — the parseImportsExports function:
import {parseImportsExports} from 'parse-imports-exports';import type {ImportsExports, Options} from 'parse-imports-exports';const importsExports: ImportsExports = parseImportsExports('some source code (as string)');// or with optional options:const importsExports = parseImportsExports('some source code (as string)', options);// all option fields are optional boolean with default `false` valueconst options: Options = { /** * If `true`, then we ignore `module.exports = ...`/`(module.)exports.foo = ...` expressions * during parsing (maybe a little faster). * By default (if `false` or skipped option), `module.exports = ...`/`(module.)exports.foo = ...` * expressions are parsed. */ ignoreCommonJsExports: false
parse-imports-exports also exports types included in the API:
export type { /** * Parsed JSON presentation of imports, exports and reexports of ECMAScript/TypeScript module. */ ImportsExports, /** * Kind of exported declaration. */ Kind, /** * Options of `parseImportsExports` function. */ Options,};