Is there a way to add or remove nodes in the source code? #4970
-
For example, adding an import statement or deleting a string literal expression. Here is my code implementation for modifying nodes: |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
I searched for all the projects and code related to oxc that I could find on GitHub, but couldn't find any related implementations. My requirement is simple, which is to add an import statement in the JS code. Should I use oxc_transformer, oxc_traverse, or oxc_parser? Do you have a minimum example. |
Beta Was this translation helpful? Give feedback.
-
cc: @overlookmotel |
Beta Was this translation helpful? Give feedback.
-
Usually you'd use But for your simple use case, either of those is overkill. I'd suggest just parsing using If you then need to print the AST back to JS text, see codegen example. Hope that helps. |
Beta Was this translation helpful? Give feedback.
Usually you'd use
oxc_ast::visit::VisitMut
for mutating AST (oxc_traverse::Traverse
would also work, but that crate's API is likely to be reworked considerably in near future, and is only really intended for internal use within Oxc at present).But for your simple use case, either of those is overkill. I'd suggest just parsing using
oxc_parser
, and then insert whatever nodes you want onto start ofprogram.body
. Please see the parser example, and then you can create new nodes usingoxc_ast::AstBuilder
.If you then need to print the AST back to JS text, see codegen example.
Hope that helps.