LogoPear Docs

bare-module-lexer

Heuristic lexer for detecting imports and exports in JavaScript modules

stable

bare-module-lexer — Heuristic lexer for detecting imports and exports in JavaScript modules. It is a native addon.

npm i bare-module-lexer

Usage

const lex = require('bare-module-lexer')

lex(`
  const foo = require('./foo.js')
  exports.bar = 42
`)

// {
//   imports: [
//     { specifier: './foo.js', type: REQUIRE, names: [], position: [ 15, 24, 32 ] }
//   ],
//   exports: [
//     { name: 'bar', position: [ 37, 45, 48 ] }
//   ]
// }

API

Functions

lex

lex(input: string | Buffer, encoding?: BufferEncoding, opts?: object): {
  imports: Import[]
  exports: Export[]
}
Source

Lex input for import and export statements, returning the detected imports and exports.

Parameters

ParameterTypeDefaultDescription
inputstring | BufferThe source to lex, as a string or buffer.
encoding?BufferEncodingThe encoding of input when it is a string.
opts?objectReserved; currently unused.

Throws

  • TypeErrorinput is not a string or buffer.

Types

Import

interface Import {
  specifier: string
  type: number
  names: string[]
  attributes: { [attribute: string]: string }
  position: [importStart: number, specifierStart: number, specifierEnd: number]
}
Source

An import detected in the source. type is a combination of the lex.constants flags (e.g. REQUIRE, IMPORT, DYNAMIC); position holds the offsets [importStart, specifierStart, specifierEnd].

Export

interface Export {
  name: string
  position: [exportStart: number, nameStart: number, nameEnd: number]
}
Source

An export detected in the source; position holds the offsets [exportStart, nameStart, nameEnd].

See also

On this page