-
Here is my code: use swc_common::FilePathMapping;
use swc_common::{sync::Lrc, FileName, SourceMap};
use swc_ecmascript::ast::{EsVersion, ImportDecl, Module};
use swc_ecmascript::codegen::text_writer::JsWriter;
use swc_ecmascript::codegen::{Config, Emitter};
use swc_ecmascript::parser::{
error::Error as SwcError, lexer::Lexer, Parser, StringInput, Syntax, TsConfig,
};
use swc_ecmascript::visit::{as_folder, FoldWith, VisitMut};
const ES_VERSION: EsVersion = EsVersion::Es2021;
struct ImportProcessor;
impl VisitMut for ImportProcessor {
fn visit_mut_import_decl(&mut self, import: &mut ImportDecl) {
import.src.value = "testaaa".into();
}
}
pub fn parse(source: String, cm: &Lrc<SourceMap>) -> Result<Module, SwcError> {
let source_file = cm.new_source_file(FileName::Real("index.js".into()), source.into());
let syntax = Syntax::Typescript(TsConfig {
decorators: true,
dts: false,
tsx: true,
no_early_errors: false,
});
let lexer = Lexer::new(syntax, ES_VERSION, StringInput::from(&*source_file), None);
let mut parser = Parser::new_from(lexer);
Ok(parser.parse_module()?)
}
pub fn visit_imports(module: Module) -> Module {
module.fold_with(&mut as_folder(ImportProcessor))
}
pub fn emit(module: &Module, cm: Lrc<SourceMap>) -> String {
let mut buf = vec![];
{
let writer = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None));
let config = Config { minify: false };
let mut emitter = Emitter {
cfg: config,
comments: None,
cm: cm.clone(),
wr: writer,
};
emitter.emit_module(&module).unwrap();
}
String::from_utf8(buf).unwrap()
}
pub fn process(source: String) -> String {
let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
match parse(source, &cm) {
Ok(module) => emit(&visit_imports(module), cm),
Err(_) => "".into(),
}
} what the ImportProcessor did is just replace all import.src with But when I call process("import {abc,a} from 'deno'".into()) the output is |
Beta Was this translation helpful? Give feedback.
Answered by
kdy1
Dec 29, 2021
Replies: 1 comment 6 replies
-
You can try debugging using |
Beta Was this translation helpful? Give feedback.
6 replies
Answer selected by
kdy1
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can try debugging using
dbg!
on ast nodes are other types.