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
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.
Yes, you may use a js parser like
esprima
and extract the exported names.like the example below: