worker-loader 不能在 react project 中使用 wasm-loader 和 Typescript



我试过了:

// 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 });
});

其中uranus-qrcode是我创建的 Rust-Wasm 模块。我使用 wasm-loader 来加载它,当我将其加载到主线程中时它可以工作,但是当我尝试使用 worker loader 时,它说:

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

现在工人化方法有效!

我最初尝试过 workerize-loader + wasm-loader,它在开发模式下运行得很好,但是一旦编译,原型就不会添加到 worker 中(怀疑这是 workerize-loader 中的一个错误,因为所有 workerized 模块的行为都是一样的(。这确实是workerize-loader中的一个错误(参见workerize-loader在编译后无法工作,版本1.2.0在生产模式下没有在worker实例上导出功能(。升级到 workerize-loader 1.2.1 后,它可以在开发和生产代码中工作。

我已经更新了主存储库:https://github.com/aeroxy/react-typescript-webassembly-starter.git

最新更新