-
I'm using swc to parse text, adjust the AST and print it back out. When I print it out I notice that the resulting code is stripped from all its comments and equally the whitespace is messed up in a lot of places. To demonstrate the comments issue, I've created the following repro sample: main.rs: use swc_ecma_ast::EsVersion;
use swc_ecma_parser::{EsConfig, Syntax};
use swc::{SwcComments, Compiler};
use swc_common::collections::AHashMap;
use swc_common::errors::ColorConfig;
use swc_common::sync::Lrc;
use swc_common::{SourceMap, FileName, errors::Handler};
fn main() {
let cm: Lrc<SourceMap> = Default::default();
let compiler = Compiler::new(cm.clone());
let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(cm.clone()));
let config = EsConfig {
jsx: true,
fn_bind: true,
import_assertions: true,
..Default::default()
};
let comments: SwcComments = Default::default();
let file = cm.new_source_file(FileName::Custom("test.js".into()), String::from("// hello"));
let program = compiler
.parse_js(
file,
&handler,
EsVersion::Es2022,
Syntax::Es(config),
swc::config::IsModule::Unknown,
Some(&comments),
)
.expect("Failed to parse JS");
let printed_code = compiler.print(
&program,
None,
None,
false,
EsVersion::Es2022,
swc::config::SourceMapsConfig::Bool(false),
&AHashMap::default(),
None,
false,
Some(&comments),
)
.expect("Failed to print");
assert_eq!("// hello", printed_code.code);
} cargo.toml: [package]
name = "tmp-swc-roundtrip"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
swc = { git = "https://github.com/swc-project/swc" }
swc_ecma_ast= { git = "https://github.com/swc-project/swc" }
swc_ecma_parser= { git = "https://github.com/swc-project/swc" }
[dependencies.swc_common]
git = "https://github.com/swc-project/swc"
features = ["tty-emitter"] I see from issues such as #2964 that up until very recently swc was aware of issues related to this so I'm not sure what I should expect to be possible. Am I not using the API correctly perhaps? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Yes, swc preserve all comments correctly. #2964 is about preserving comments when they should be stripped |
Beta Was this translation helpful? Give feedback.
Yes, swc preserve all comments correctly.
#2964 is about preserving comments when they should be stripped