failed to load wasm application

Tags: , , , ,



I’m trying to host a website, and I use a .wasm file with .js scripts created by the wasm-pack tool.

I tested the project locally with npm and node.js and everything worked fine.

But Then I hosted it on a raspberry (apache2), and when I try to access it, I get in the console:

Failed to load module script: The server responded with a non-JavaScript MIME type of "application/wasm". Strict MIME type checking is enforced for module scripts per HTML spec.

details

There are multiple files, but here is the idea:

my index.html loads the module bootstrap.js

// bootstrap.js content
import("./index.js").catch(e => console.error("Error importing `index.js`:", e));

my main code is in the index.js, wich call test_wasm_bg.js

And finally, test_wasm_bg.js loads the wasm file in this line:

// test_wasm_bg.js first line
import * as wasm from './test_wasm_bg.wasm';

Where is the problem?

Is there a better way to load a .wasm file?

Edit 2

I now know that I have to instantiate “manually” my .wasm application:

I tried the command WebAssembly.instantiateStreaming(fetch('test_wasm_bg.wasm'), {}) but now I get the following error:

Uncaught (in promise) TypeError: WebAssembly.instantiate(): Import #0 module="./test_wasm_bg.wasm" error: module is not an object or function

What can I do? Does it have something to do with the test_wasm_bg.wasm.d.ts typescript file generated in my project?

Answer

I finally found what is the right way to load a wasm application with a wasm-bindgen project!

In fact, everything was on this page: https://rustwasm.github.io/docs/wasm-bindgen/reference/deployment.html

When you compile the project without wanting to run it with a bundler, you have to run wasm-pack build --release --target web.

This create a .js file (test_wasm.js in my example) with everything you need to load the wasm-application.

And you just have to create an index.js file that do stuff with the wasm module like so:

import init from '../pkg/test_wasm.js';
import {ex_function1, ex_function2 …} from '../pkg/test_wasm.js';

async function run{
await init();

// do stuff with the functions ex_function1 and ex_function2

}

run();

And finally, you include it in your HTML file (<script type="module" src="./index.js"></script>)

Here you have it.

I hope this will help someone later …



Source: stackoverflow