Error importing wasm (Wasm-bindgen) for web error

So I have been learning Rust Wasm, and started this example: Wasm Game of Life.

I got it working, no issue there. However, I do not want to use a JS Bundler, and the example is using webpack.

So I build for web for importing as static file
wasm-pack build --release --target web

My code was built fine. However, I ran into two error.

First, I cannot init an object:
Uncaught TypeError: Cannot read properties of undefined (reading 'obj_new') at Obj.new

Pretty much what I did was:

import {Obj} from "./pkg/test_wasm.js";
const obj = Obj.new();

And it failed at:

 static new() {
        const ret = wasm.obj_new(); <-- crash here
        return Obj.__wrap(ret);
    }

Basically, it did not work, at the first line after import. Honestly I am lost. I can't event init the object.
Any help would be appreciated.

Second, I cannot import memory:
In the example with JS bundle, I can do something like:
import { memory } from "test_wasm/test_wasm_bg";

Did not really work. I tried to import memory from the typescript file:
import {memory} from "./pkg/test_wasm_bg.wasm.d.ts";

And I got:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "video/mp2t". Strict MIME type checking is enforced for module scripts per HTML spec.

So yeah, I ran into two big issues.
Anyhelp is appreciated. Thank you.

1 Like

WebAssembly imports must be asyhcnronous, otherwise they don't work. In a recent project, I had the following helper embedded in my front page for simplicity:

    <script type="text/javascript">
      async function run() {
        // initialize WebAssembly module
        await wasm_bindgen("<%= BASE_URL %>ecg_eval/ecg_eval_wasm_bg.wasm");
        console.log(wasm_bindgen);
      }

      run();
    </script>

This isn't great, because you don't get notified when the import is actually complete, but this was fine in my particular case. You can set up something similar to test whether the WASM module has been loaded successfully.

1 Like

You need to call the generated init function first to actually load the wasm and perform the bindgen setup

https://rustwasm.github.io/docs/wasm-bindgen/examples/without-a-bundler.html

1 Like

Awesome. This actually solved my first problem.
However, the 2nd problem of loading memory from the *_bg file, do you know how to solve them?
I could do this with JS bundler

// Import the WebAssembly memory at the top of the file.
import { memory } from "wasm-game-of-life/wasm_game_of_life_bg";

// ...

But not sure about web release.

Thank you

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.