I want to replace URLs that declare import closures in the JS code.
How to deal?
Ideally you want something like Babel that can transpile JavaScript. In other words, a parser that can produce an AST which can be transformed in various ways and output as new JavaScript.
I don't know of any Babel-like projects written in Rust. In the worst case, you can probably just run Babel through deno
. The boa
project has some of the fundamental pieces for it. Maybe that's something to look into?
You might be able to use swc
, seems like it is a popular Babel alternative written in Rust.
I tried to use swc, but I can't find the import declaration with it.
use swc_common::{
DUMMY_SP,
source_map::SourceMap
};
use swc_ecma_parser::{Parser, StringInput, lexer::Lexer, EsSyntax};
use swc_ecma_codegen::{Emitter, text_writer::JsWriter};
use swc_ecma_ast::*;
use swc_ecma_visit::{VisitMut, VisitMutWith};
use dprint_swc_ext::common::StartSourcePos;
use std::sync::Arc;
struct ImportRewriter {
new_url: String,
}
impl VisitMut for ImportRewriter {
fn visit_mut_module_decl(&mut self, n: &mut ModuleDecl) {
if let ModuleDecl::Import(import_decl) = n {
// Check if the import source matches a specific pattern
if import_decl.src.value == "./module.js" {
// Modify the import source
import_decl.src = Box::new(Str {
span: DUMMY_SP,
value: self.new_url.clone().into(),
raw: None,
});
}
}
n.visit_mut_children_with(self);
}
}
fn main() {
let raw_js_str = "import { name1, name2 } from './module.js';
const qs = require('qs');".to_string();
let new_url = "/new/path/to/module.js".to_string();
let start = StartSourcePos::START_SOURCE_POS;
let end = start + raw_js_str.len();
let string_input = StringInput::new(
&raw_js_str,
start.as_byte_pos(),
end.as_byte_pos()
);
let lexer = Lexer::new(
swc_ecma_parser::Syntax::Es(EsSyntax { ..Default::default() }),
EsVersion::Es2020,
string_input,
None);
let mut parser = Parser::new_from(lexer);
let mut module = match parser.parse_module() {
Ok(module) => module,
Err(err) => panic!("Failed to parse JavaScript code: {:?}", err),
};
// Traverse and modify the AST
module.visit_mut_with(&mut ImportRewriter { new_url });
println!("{:?}", module);
}