Import WASM into webworker synchronously using Webpack
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);