ast-types icon indicating copy to clipboard operation
ast-types copied to clipboard

Question: Finding ES6 Import statements

Open mainrs opened this issue 6 years ago • 3 comments

I used babel-types, babel-generator, babylon and babel-traverse to find ImportDeclarations within ES6 code. But I need to preserve the formatting of the original file. So I came across recast and it looks like this might be a good library for my use case. But I can't figure out how to traverse for ImportDeclarations. I looked into defs/core.js and I couldn't find any ImportDeclaration specific definitions. Is this something babel specific? SOme help would be really nice as I am quite new to AST manipulation and JS in general.

mainrs avatar Feb 05 '18 10:02 mainrs

You might want to take a look at https://github.com/benjamn/ast-types/blob/master/def/esprima.js#L47-L61 and https://github.com/benjamn/ast-types/blob/master/def/esprima.js#L81-L95.

bnjmnt4n avatar Feb 06 '18 09:02 bnjmnt4n

Thanks! Would I need to specify the esprima library as the parser by passing it in the hash? { parser: esprima }?

mainrs avatar Feb 06 '18 10:02 mainrs

I believe the AST format for import declarations are quite similar between different parsers, although I can't be too sure. If you want you can also look at Babel's AST: https://github.com/benjamn/ast-types/blob/b46647f9bb8bd15202f47ad77830be27c8acb15c/def/babel-core.js#L54-L65 and the supertype for both Babel and Esprima: https://github.com/benjamn/ast-types/blob/859a2b2bd37dfc95d0b338c8093b8f245e241675/def/es6.js#L195-L209.

bnjmnt4n avatar Feb 06 '18 14:02 bnjmnt4n