ast-types
ast-types copied to clipboard
Question: Finding ES6 Import statements
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 ImportDeclaration
s. 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.
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.
Thanks! Would I need to specify the esprima library as the parser by passing it in the hash? { parser: esprima }
?
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.