rustwasm / book

The Rust and WebAssembly Book
https://rustwasm.github.io/docs/book/
MIT License
1.75k stars 211 forks source link

Example to call Rust from JS and back? #244

Open ivnsch opened 3 years ago

ivnsch commented 3 years ago

I'm trying to adapt the tutorial to call user-defined JS (instead of alert) from Rust:

index.js:

import * as wasm from "testing-wasm";

export const jsfunc = () => {
  console.log("jsfunc called");
};

// Call Rust from JS. This function will call `jsfunc`, declared above.
wasm.rustfunc();

lib.rs:

mod utils;

use wasm_bindgen::prelude::*;

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

#[wasm_bindgen(module = "/www/index.js")]
extern "C" {
    fn jsfunc();
}

#[wasm_bindgen]
pub fn rustfunc() {
    // call JS
    jsfunc();
}

wasm-pack build runs fine. But running the web project (npm run start) can't resolve the import anymore:

ERROR in ../pkg/snippets/testing-wasm-8ea926e8de57779d/www/index.js
Module not found: Error: Can't resolve 'testing-wasm' in '/Users/ischuetz/dev/ct-an/testing-wasm/pkg/snippets/testing-wasm-8ea926e8de57779d/www'
 @ ../pkg/snippets/testing-wasm-8ea926e8de57779d/www/index.js 1:0-37 7:0-13
 @ ../pkg/testing_wasm_bg.wasm
 @ ../pkg/testing_wasm.js
 @ ./index.js
 @ ./bootstrap.js

It works before introducing the circular dependency.

It would be great if you could add an example of this to the tutorial (use case allowing of course). This flow (call Rust, which calls JS back) should be used frequently and it surprisingly hard to find examples. There's e.g. import_js in wasm-bindgen but there there's no direct call to Rust from JS.

9SMTM6 commented 3 years ago

I think youre looking for the Wasm-Bindgen Reference. Btw, I think your approach is problematic. Either you want to declare the JS-Function with a JS-Snippet/Inline-JS or you want to give a Callback to the Rust-Funktion.

ivnsch commented 3 years ago

There seems to be something problematic with wasm-bindgen (used with webpack?). See https://github.com/rustwasm/wasm-bindgen/issues/2375#issuecomment-736861169