I've tried:
// Worker.ts
// @ts-ignore
// eslint-disable-next-line no-restricted-globals
const ctx: Worker = self as any;
// Post data to parent thread
// ctx.postMessage({ foo: "foo" });
// Respond to message from parent thread
ctx.addEventListener('message', async ({ data }) => {
const {
href,
width,
height
} = data;
const { qrcode } = await import('uranus-qrcode');
const qr = qrcode(href, width, height);
ctx.postMessage({ href, qr });
});
in which uranus-qrcode
is a Rust-Wasm module I created. I use wasm-loader to load it, and it works when I load it into the main thread, but when I tried it with worker-loader it says:
Uncaught (in promise) TypeError: Cannot read property './modules/uranus_qrcode/uranus_qrcode_bg.wasm' of undefined
at Object../modules/uranus_qrcode/uranus_qrcode_bg.wasm (http://localhost:3334/0.34621aa454b5fe6ea3b4.worker.js:145:40)
at __webpack_require__ (http://localhost:3334/34621aa454b5fe6ea3b4.worker.js:34:30)
at Module../modules/uranus_qrcode/uranus_qrcode.js (http://localhost:3334/0.34621aa454b5fe6ea3b4.worker.js:12:80)
at __webpack_require__ (http://localhost:3334/34621aa454b5fe6ea3b4.worker.js:34:30)
at async http://localhost:3334/34621aa454b5fe6ea3b4.worker.js:139:7
Now the workerize method works!
I've originally tried workerize-loader + wasm-loader, and it works pretty well in the dev mode but once it is compiled, the prototype will not be added to the worker (suspecting it's a bug in workerize-loader because all workerized modules behave the same). This indeed turns out to be a bug in workerize-loader (see workerize-loader failed to work after compiling and Version 1.2.0 does not export function on worker instance in production mode). After upgrading to the workerize-loader 1.2.1, it works in both dev and prod code.
I have updated the Master repo: https://github.com/aeroxy/react-typescript-webassembly-starter.git