首页 > 解决方案 > 创建 React App 导入 Wasm 到 Web Worker

问题描述

我正在使用 wasm-bindgen 和一个 react 应用程序(使用 create-react-app 创建),我想将一个 wasm 模块导入到 web worker 中。

我正在使用这个例子,只是为了开始。

为了在“主线程”上使用 wasm,我设置了 react-app-rewired,这里是 config-overrides.js:

const path = require('path');

module.exports = function override(config, env) {
    const wasmExtensionRegExp = /\.wasm$/;

    config.resolve.extensions.push('.wasm');

    config.module.rules.forEach(rule => {
        (rule.oneOf || []).forEach(oneOf => {
            if (oneOf.loader && oneOf.loader.indexOf('file-loader') >= 0) {
                // Make file-loader ignore WASM files
                oneOf.exclude.push(wasmExtensionRegExp);
            }
        });
    });

    // Add a dedicated loader for WASM
    config.module.rules.push({
        test: wasmExtensionRegExp,
        include: path.resolve(__dirname, 'src'),
        use: [{ loader: require.resolve('wasm-loader'), options: {} }]
    });

    return config;
};

在主线程上,我可以导入 wasm 并在本地 npm 链接之后像这样使用它(没有发布任何 npm 模块):

const wasm = import('my_wasm_package')

wasm.then(w => w.call__some_function())

我读到您应该在主线程中编译 wasm 模块,然后将其 postMessage 到线程,所以我尝试了以下操作:

fetch("my_wasm_package").then(response =>
  response.arrayBuffer()
).then(bytes =>
  WebAssembly.compile(bytes)
).then(WasmModule =>
  myWorker.postMessage(WasmModule)
);

这给了我以下错误:

localhost/:1 Uncaught (in promise) CompileError: WebAssembly.compile(): expected magic word 00 61 73 6d, found 3c 21 44 4f @+0

我也尝试了正常的导入命令:

const wasm = import('my_wasm_package')

wasm.then(w => {

   myWorker.postMessage(w)

})

我收到以下错误:

Uncaught (in promise) DOMException: Failed to execute 'postMessage' on 'Worker': function greet() {
  _satellite_rust_bg_wasm__WEBPACK_IMPORTED_MODULE_0__["greet"]();
} could not be cloned.
    at

有什么我可以添加到 webpack.config 以使其工作的吗?什么是正确的设置?

标签: rustweb-workerwebassemblywasm-bindgenrust-wasm

解决方案


推荐阅读