Notification texts go here Contact Us Buy Now!

How can I get comments from swc_ecma_parser

The comments are indeed not part of the AST, but the parser handles them separately. The third argument of Parser::new is comments: Option<&'a dyn Comments>. In your code you provide Default::default() here, which is simply None for an Option, suppressing any comment parsing. You can instead create one of the implementations of the Comments trait, such as SingleThreadedComments:

let comments: swc_common::comments::SingleThreadedComments = Default::default();
let mut parser = Parser::new(
    Syntax::Typescript(ts_config),
    StringInput::from(&*fm),
    Some(&comments),
);

After invoking the parser, comments should be updated (the API uses a shared reference for reasons). You should be able to mutably iterate through the comments using borrow_all_mut.

Finally, it seems like swc::Compiler::print is the method you will want to use to convert the AST back into code. Again, this method accepts comments: Option<&dyn Comments> as its last argument.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.