6.4 Transpile
Overview
Transpile
pub fn transpile(&self, options: &EmitOptions) -> Result<TranspiledSource> {
let program = (*self.program()).clone();
let source_map = Rc::new(SourceMap::default());
let source_map_config = SourceMapConfig {
inline_sources: options.inline_sources,
};
let file_name = match ModuleSpecifier::parse(self.specifier()) {
Ok(specifier) => FileName::Url(specifier),
Err(_) => FileName::Custom(self.specifier().to_string()),
};
source_map.new_source_file(file_name, self.text_info().text().to_string());
// needs to align with what's done internally in source map
assert_eq!(1, self.text_info().range().start.as_byte_pos().0);
// we need the comments to be mutable, so make it single threaded
let comments = self.comments().as_single_threaded();
let globals = Globals::new();
crate::swc::common::GLOBALS.set(&globals, || {
let top_level_mark = Mark::fresh(Mark::root());
let program = fold_program(
program,
options,
source_map.clone(),
&comments,
top_level_mark,
self.diagnostics(),
)?;
let mut src_map_buf = vec![];
let mut buf = vec![];
{
let mut writer = Box::new(JsWriter::new(
source_map.clone(),
"\n",
&mut buf,
Some(&mut src_map_buf),
));
writer.set_indent_str(" "); // two spaces
let config = crate::swc::codegen::Config {
minify: false,
ascii_only: false,
omit_last_semi: false,
target: ES_VERSION,
};
let mut emitter = crate::swc::codegen::Emitter {
cfg: config,
comments: Some(&comments),
cm: source_map.clone(),
wr: writer,
};
program.emit_with(&mut emitter)?;
}
let mut src = String::from_utf8(buf)?;
let mut map: Option<String> = None;
{
let mut buf = Vec::new();
source_map
.build_source_map_with_config(&src_map_buf, None, source_map_config)
.to_writer(&mut buf)?;
if options.inline_source_map {
src.push_str("//# sourceMappingURL=data:application/json;base64,");
base64::encode_config_buf(
buf,
base64::Config::new(base64::CharacterSet::Standard, true),
&mut src,
);
} else {
map = Some(String::from_utf8(buf)?);
}
}
Ok(TranspiledSource {
text: src,
source_map: map,
})
})
}
Transpile hello world v2
Output
Last updated