-
Hi! I'm writing a plugin for SWC where I need to read values from a json file and then create a variable with those values. Here I create a new variable and add it to the statements list : impl TransformVisitor {
fn visit_mut_stmt_like<T>(&mut self, stmts: &mut Vec<T>)
where
Vec<T>: VisitMutWith<Self>,
T: StmtLike + VisitMutWith<TransformVisitor>,
{
let mut stmts_updated = Vec::with_capacity(stmts.len());
for mut stmt in stmts.take() {
stmt.visit_mut_with(self);
stmts_updated.push(stmt);
}
if self.should_create_mapped_class_obj {
let object_map_name = quote_ident!(DUMMY_SP, self.style_import_name.clone());
let obj_props = self
.css_module_map
.iter()
.map(|(key, value)| {
let key = key.clone();
let value = value.name.clone();
PropOrSpread::Prop(Box::new(Prop::KeyValue(KeyValueProp {
key: PropName::Ident(quote_ident!(DUMMY_SP, key)),
value: Box::new(value.into()),
})))
})
.collect();
/*
* Create a new object with the compiled class names, ie:
* `const styles = { foo: "foo_1", bar: "bar_1" }`
*/
let style_object = Stmt::Decl(Decl::Var(Box::new(VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Const,
declare: false,
decls: vec![VarDeclarator {
span: DUMMY_SP,
name: object_map_name.into(),
init: Some(Box::new(Expr::Object(ObjectLit {
span: DUMMY_SP,
props: obj_props,
}))),
definite: false,
}],
})));
stmts_updated.push(T::from_stmt(style_object));
}
*stmts = stmts_updated;
}
} And when I implement the fn visit_mut_stmts(&mut self, node: &mut Vec<Stmt>) {
self.visit_mut_stmt_like(node);
}
fn visit_mut_module_items(&mut self, node: &mut Vec<ModuleItem>) {
self.visit_mut_stmt_like(node);
} If I log the Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Above code looks legit. Especially, if you could see ast updated in the visitor it may likely something else is going on. |
Beta Was this translation helpful? Give feedback.
-
Sorry for the late update. No idea what happened but the same code now works as expected :| |
Beta Was this translation helpful? Give feedback.
Sorry for the late update. No idea what happened but the same code now works as expected :|