Simon H
Simon H

Reputation: 21005

Import WASM into webworker synchronously using Webpack

I've been following the wasm_bindgen guides to create wasm from rust. Those work fine and I have some code that can be loaded in my main app.

That loading works sometimes, but frequently not, with my main program's initialization hanging. A race condition?

We are loading the wasm directly into a webworker. So, whereas as normally wasm has to be loaded asynchronously, that requirement does not hold within web-workers. Forcing synchronous loading is what I would like to do to see whether this creates more consistent behavior, whatever the performance consequences

Here's my setup

// pkg contains the assets from the wasm_bindgen example
import {greet} from "./pkg";
console.log("****after import")
function ffi_greet(connector, args) {
    console.log("*****GREET*********", args)
    return greet(args[0])
}

In my webpack.config.js I have:

        experiments: {
            asyncWebAssembly: true,
        }

The code does look synchronous, but I presume that webpack is loading wasm asynchronously. My question is how can I force synchronous wasm loading (in a webworker)

Upvotes: 2

Views: 1875

Answers (1)

Renato
Renato

Reputation: 13690

While wasm-pack tries to make it easy to automate the loading of the WASM code into your application, it still allows applications to fairly freely change how it does it.

For example, in one of the applications we wrote at work, we decided to embed the WASM binary into the HTML page itself (we had reasons).

The WASM loader looks like this:

webpack.wasm-loader.js

module.exports = function (buffer) {
    const wasm = buffer.toString('base64');
    return `module.exports = Uint8Array.from(atob('${wasm}'), c => c.charCodeAt(0));`;
};

Then, in webpack.config.js:

    module: {
        rules: [{
            test: /\.wasm$/,
            use: [{
                loader: path.resolve('webpack.wasm-loader.js'),
            }]
        }],
    },

The initializer script does something like this:

import init from '../pkg/my_lib';
import wasm from '../pkg/my_lib_bg.wasm';

init(wasm);

Upvotes: 1

Related Questions