4

I'm working with rust, WASM, and yew as frontend framework. I'm building a wrapper around materialize-css, to use it on yew as dependency of reusable components.

To use some materialize-css components it's necesary initialize it. For example, to use a sidenav

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.sidenav');
    var instances = M.Sidenav.init(elems, options);
  });

The thing is that I'm trying to run that with wasm-bindgen as described in the wasm-bindgen docs, but it doesn't work. Or maybe I do not really understand whats happening.

according to the documentation, this should work:

#[wasm_bindgen( module = "/materialize/js/bin/materialize.js", js_namespace = ["M","Sidenav"] )]
extern "C" {
  fn init(el: JsValue, options: JsValue);
}

pub unsafe fn init_sidenav(el: &str, options: &str) {
    init(
        JsValue::from(document().get_element_by_id(el).expect("not found")),
        JsValue::from(options),
    );
}
//to use it on yew component
unsafe { materialize::sidenav::init_sidenav(self.props.el_id, &options) };

or this:

#[wasm_bindgen( module = "/materialize/js/bin/materialize.js", js_namespace = M )]
extern "C" {
  #[wasm_bindgen]
  type Sidenav;

  #[wasm_bindgen( static_method_of = Sidenav )]
  fn init(el: JsValue, options: JsValue);
}

pub unsafe fn init_sidenav(el: &str, options: &str) {
    Sidenav::init(
        JsValue::from(document().get_element_by_id(el).expect("not found")),
        JsValue::from(options),
    );
}
//to use it on yew component
unsafe { materialize::sidenav::init_sidenav(self.props.el_id, &options) };

But neither of them works... In both cases the code compiles without problems but when executed in the browser it jumps errors.

in the first case the error is Uncaught SyntaxError: import not found: init lib.js:1:9

in the second case the error is Uncaught SyntaxError: import not found: Sidenav lib.js:1:9

honestly i dot not understand why this happens. I've been looking for some days for information in the MDN docs about WASM, and the wasm_bindgen docs, but I can't find anything that helps me.

Additionally

I'm working with --target web flag

My project structure

-
|Cargo.toml
|materialize/ (source of materialize-css dist)
|src/
|-components/ (wrappings of components on yew)
|-materialize/ (wasm-bindgen bindings of materialize)
|-lib.rs
|-...
...
al3x
  • 589
  • 1
  • 4
  • 16

0 Answers0