70 %
Chris Biscardi

Replacing ImportDecl names with SWC's Fold trait

As part of Toast I needed to port a babel plugin that included rewriting some imports from one target to another. This is a simple version of the transformation I needed to make happed in a JS file:

JS
import Thing from "preact";

to

JS
import Thing from "not-preact";

Here's the code I used to do it in Rust

swc_import_map_rewrite.rs
rust
use std::path::Path;
use string_cache::Atom;
use swc_ecma_ast::{ImportDecl, Str};
use swc_ecma_visit::{noop_fold_type, Fold};
pub struct SWCImportMapRewrite<'a> {
pub import_map: &'a Path,
}
impl Fold for SWCImportMapRewrite<'_> {
noop_fold_type!();
fn fold_import_decl(
&mut self,
imports: ImportDecl,
) -> ImportDecl {
ImportDecl {
src: Str {
value: Atom::from("not-preact"),
..imports.src
},
..imports
}
}
}
somewhere_else.rs
rust
program.fold_with(&mut SWCImportMapRewrite {
import_map: Path::new("thing"),
})