webpackvitewebassemblyweb-workerrust-wasm

WASM module not loaded inside web worker


I'm failing to load a simple WASM function, which sums two numbers, inside my web worker.

I tried it inside my main/index script which is working fine. However, moving the code into the web worker breaks the code. It seems like that the sum() code is not executed inside my web worker. However I do not get any helpful logs or error messages to further debug the code. For a better understanding here is my example-repository

For example, running the vite code shows me this logs:

[vite] connecting... client.ts:19:8
Message posted to worker with numbers 1 and 2. main.ts:13:10
[vite] connected. client.ts:175:14

I would expect more log lines here as soon as postMessage() on the web worker is executed. It seems like the web worker is stopping when calling the wasm module.

Any ideas? Thanks so far!

Update:

Seems to be a timing issue (at least for the vite plugin). Setting a breakpoint in the main script gives me all the desired console outputs:

Message posted to worker with numbers 1 and 2.
worker.ts:4 Worker is calculating with data... {number1: 1, number2: 2}
main.ts:20 Message received, sum is:  3

However it does not look like this fixes the webpack module. Additionally I dont know why this is happening and how to fix it without breakpoints...


Solution

  • I think I fixed the issue. The import was the problem.

    Using dynamic import instead of static import is working for me:

    onmessage = (msg: MessageEvent<{ number1: number; number2: number }>) => {
      import("wasm-sum").then((wasm) => {
        console.log("Worker is calculating with data...", msg.data);
        const sum = wasm.sum(msg.data.number1, msg.data.number2);
        postMessage(sum);
      });
    };
    

    I've updated my example-repository.

    AS a alternative i should have used a module web worker instead of a classic one...