0

I need to set attributes on elements.

fn visit_mut_jsx_opening_element(&mut self, n: &mut JSXOpeningElement){

}

JSXOpeningElement finds all opening elements

Please see its content - https://rustdoc.swc.rs/swc_ecma_ast/struct.JSXOpeningElement.html

Fragment from the documentation:

pub struct JSXOpeningElement {
    pub name: JSXElementName,
    pub span: Span,
    pub attrs: Vec<JSXAttrOrSpread>,
    pub self_closing: bool,
    pub type_args: Option<Box<TsTypeParamInstantiation>>,
}

I see that to add an attribute you need to set n.attrs.

Type: vector with type JSXAttrOrSpread

fn visit_mut_jsx_opening_element(&mut self, n: &mut JSXOpeningElement){
     n.attrs = vec![];
}

It works! I'm removing the attributes because I'm passing in an empty vector.

But I need to create an attribute. Everything I pass to the vector causes an error

JSXAttrOrSpread documentation - https://rustdoc.swc.rs/swc_ecma_ast/enum.JSXAttrOrSpread.html

JSXAttr documentation - https://rustdoc.swc.rs/swc_ecma_ast/struct.JSXAttr.html

I tried like this:

1.

fn visit_mut_jsx_opening_element(&mut self, n: &mut JSXOpeningElement){
     n.attrs = vec![JSXAttr(Ident::new("className".into(), n.span).into())];
}
// error - error[E0277]: the trait bound `swc_core::ecma::ast::JSXAttr: From<swc_core::ecma::ast::Ident>` is not satisfied
fn visit_mut_jsx_opening_element(&mut self, n: &mut JSXOpeningElement){
     n.attrs = vec![JSXAttr("className".into())];
}
// error[E0277]: the trait bound `swc_core::ecma::ast::JSXAttr: From<&str>` is not satisfied
fn visit_mut_jsx_opening_element(&mut self, n: &mut JSXOpeningElement){
     n.attrs = vec![JSXAttr(JSXAttrName::Ident(Ident::new("className".into(),n.span).into()))];
}
// expected struct `JSXAttr`, found enum `JSXAttrName`

Help me please. I'm in pain for days

I am using the latest version of rust, swc, cargo

Jmb
  • 18,893
  • 2
  • 28
  • 55
Roman
  • 175
  • 2
  • 3
  • 15

0 Answers0