Carsten
Carsten

Reputation: 103

How to import wasm in web workers with webpack?

is it possible with webpack to import wasm in workers? In my normal js code i can import wasm like this:

import('../wasm/hello_world.wasm').then(module => {
    console.log(module.add_one(9))
})

the same code does not work inside a worker. It returns the following error message:

Uncaught TypeError: Cannot read property './src/wasm/hello_world.wasm' of undefined

My webpack config is a combination of the webpack worker and wasm examples.

Upvotes: 5

Views: 2786

Answers (1)

Wolfie Wolf
Wolfie Wolf

Reputation: 81

Based on the original question and the comment it looks like there is interest in solving this for both C / Emscripten and Rust compiled WASM.

I found the following article that explains very nicely how to achieve the results for Emscripten generated wasm here:

https://medium.com/@c.gerard.gallant/webassembly-web-workers-f2ba637c3e4a

As for Rust, I was going to come up with my own solution to this and provide a github repo to accompany my answer but during the course of my research I discovered that this developer had already solved the problem quite nicely already and kindly provided us with a ready to use template.

Thank you Victor Gavrish!

https://github.com/VictorGavrish/rust-wasm-worker-template

The steps in the README.md are a little out of date. I was able to build and run the project by doing the following:

clone the repo locally and execute:

cd rust-wasm-worker-template/www
npm install
npm run build
npm run start

Once webpack is finished bundling everything the dev site will be available from the URL provided on the console.

The important things to remember, in general, are the limitations of webworkers. There is no direct access to the dom or console, you have to handle passing messages from the worker to the main thread and then output to console. I mention this specifically because the OP used an example that called console.log...

Upvotes: 3

Related Questions