4

I'm working with wasm-bindgen and a react app (created with create-react-app) and I'd like to import a wasm module into a web worker.

I'm using this example, just to start out.

To work with wasm on the "main-thread" I set up react-app-rewired, here's the config-overrides.js:

const path = require('path');

module.exports = function override(config, env) {
    const wasmExtensionRegExp = /\.wasm$/;

    config.resolve.extensions.push('.wasm');

    config.module.rules.forEach(rule => {
        (rule.oneOf || []).forEach(oneOf => {
            if (oneOf.loader && oneOf.loader.indexOf('file-loader') >= 0) {
                // Make file-loader ignore WASM files
                oneOf.exclude.push(wasmExtensionRegExp);
            }
        });
    });

    // Add a dedicated loader for WASM
    config.module.rules.push({
        test: wasmExtensionRegExp,
        include: path.resolve(__dirname, 'src'),
        use: [{ loader: require.resolve('wasm-loader'), options: {} }]
    });

    return config;
};

On the main thread I can import wasm and use it like this after a local npm link (did not publish any npm module):

const wasm = import('my_wasm_package')

wasm.then(w => w.call__some_function())

I read you're supposed to compile the wasm module in the main thread and then postMessage it to the thread, so I tried the following:

fetch("my_wasm_package").then(response =>
  response.arrayBuffer()
).then(bytes =>
  WebAssembly.compile(bytes)
).then(WasmModule =>
  myWorker.postMessage(WasmModule)
);

This gives me the following error:

localhost/:1 Uncaught (in promise) CompileError: WebAssembly.compile(): expected magic word 00 61 73 6d, found 3c 21 44 4f @+0

I also tried with the normal import command:

const wasm = import('my_wasm_package')

wasm.then(w => {

   myWorker.postMessage(w)

})

And I get the following error:

Uncaught (in promise) DOMException: Failed to execute 'postMessage' on 'Worker': function greet() {
  _satellite_rust_bg_wasm__WEBPACK_IMPORTED_MODULE_0__["greet"]();
} could not be cloned.
    at

Is there anything I could add to the webpack.config to make it work? what is the correct set up ?

Mattia
  • 179
  • 15

0 Answers0