skip to Main Content

So let’s say we have some JavaScript es module as text

const ESMText = "export const answer = 42;"

I checked ECMAScript documents, and logic for export is quite complicated, is there kinda simple way to finde out all exports without executing it or implementing almost full spec lexical analysis stuff (tokenizer, etc…) ?


It should be done in browser using JavaScript (maybe wasm)


Should be mentioned: obviously parse file using existing parser is the right answer, but whole point of question is to find kinda tricky way to do it


it could be easy done with regex, but there is two edge cases that i can’t handle:

// destructuring assignment
export const { name1, name2: bar } = o;
export const [ name1, name2 ] = array;

//simultaneous declaration and assignment
export const name1 = 1, name2 = 2/*, … */;

may be someone will figure out something of it

2

Answers


  1. There are many JavaScript parsers: acorn, esprima, Babel, etc. Your best bet is probably to use one of them.

    https://astexplorer.net/ lets you experiment with different parsers to see the abstract syntax trees that they generate.

    Login or Signup to reply.
  2. Yes, you may use a js parser like esprima and extract the exported names.

    like the example below:

    const esprima = require('esprima');
    
    function getExportedNames(jsCode) {
      const parsedCode = esprima.parseScript(jsCode, { sourceType: 'module' });
    
      const exportedNames = parsedCode.body.filter(node => node.type === 'ExportNamedDeclaration')
        .map(exportNode => exportNode.specifiers.map(spec => spec.exported.name))
        .reduce((acc, curr) => acc.concat(curr), []);
    
      return exportedNames;
    }
    
    const ESMText = "export const answer = 42;export function foo() {}"
    const exportedNames = getExportedNames(ESMText);
    console.log(exportedNames); // output:  ['answer', 'foo']
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search