rust - worker-loader 不能在 react 项目中使用 wasm-loader 和 typescript

标签 rust react-scripts wasm-bindgen worker-loader

我试过了:

// 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 方法起作用了!

我最初尝试过workerize-loader + wasm-loader,它在dev模式下工作得很好,但是一旦编译,原型(prototype)就不会添加到worker中(怀疑这是workerize-loader中的一个错误,因为所有工作模块行为相同)。这确实是 workerize-loader 中的一个错误(参见 workerize-loader failed to work after compilingVersion 1.2.0 does not export function on worker instance in production mode )。升级到 workerize-loader 1.2.1 后,它适用于开发和产品代码。

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

关于rust - worker-loader 不能在 react 项目中使用 wasm-loader 和 typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61820320/

相关文章:

javascript - 运行 react-scripts start 后如何停止?

reactjs - 在 React 应用程序中运行 npm start 时出现 babel-jest 依赖问题

reactjs - postcss 7.0.0 - 8.2.9 严重性 : moderate Regular Expression Denial of Service

javascript - Rust wasm : How to access Webassembly. 当前实例的内存(来自 Rust)?

postgresql - 在Rust中将时间戳吸收到postgres时,如何避免字符串转换?

rust - "the size for values of type cannot be known at compilation time"尝试从函数返回 dyn Traits 向量时

rust - 未装箱的闭包类型各不相同

rust - 在处理嵌套选项类型时,如何减少代码的嵌套?

Rust Wasm Bindgen 返回对象但获取一个数字

rust - 类型不匹配解决 future_to_promise