-
Hey, I'm writing a small plugin to wrap code into a block statement: Plugin sourceuse swc_core::ecma::ast::{BlockStmt, Module, ModuleItem, Stmt};
use swc_core::ecma::{ast::Program, transforms::testing::test_inline};
use swc_core::plugin::{plugin_transform, proxies::TransformPluginProgramMetadata};
use swc_core::quote;
use swc_ecma_visit::{as_folder, noop_visit_mut_type, VisitMut, VisitMutWith};
struct Transformer {}
impl VisitMut for Transformer {
noop_visit_mut_type!();
fn visit_mut_module(&mut self, node: &mut Module) {
let block_body = node
.body
.clone()
.into_iter()
.filter_map(|module_item| {
return match module_item {
ModuleItem::Stmt(stmt) => Some(stmt),
_ => None,
};
})
.collect();
node.body = vec![
quote!("const test = {}" as ModuleItem),
BlockStmt {
stmts: block_body,
..Default::default()
}
.into(),
];
}
}
#[plugin_transform]
pub fn process_transform(
mut program: Program,
_metadata: TransformPluginProgramMetadata,
) -> Program {
let mut plugin = Transformer {};
program.visit_mut_with(&mut plugin);
return program;
}
test_inline!(
Default::default(),
|_| as_folder(Transformer {}),
test,
// Input
r#"test.foo = 123"#,
// Expected
r#"
const test = {}
{
test.foo = 123
}
"#
); Then js code: const source = 'test.foo = 123'
const output = await transform(source, {
jsc: {
target: 'esnext',
experimental: {
plugins: [[fileURLToPath(import.meta.resolve('transformer')), {}]],
},
},
}) Will produce: const test1 = {};
{
test.foo = 123;
} Questions:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
For 2, it's recommended to apply a resolver before your plugin while testing. https://swc.rs/docs/plugin/ecmascript/cheatsheet#apply-resolver-while-testing |
Beta Was this translation helpful? Give feedback.
-
For |
Beta Was this translation helpful? Give feedback.
For 2, it's recommended to apply a resolver before your plugin while testing. https://swc.rs/docs/plugin/ecmascript/cheatsheet#apply-resolver-while-testing