rust - 创建 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 以使其工作的吗?什么是正确的设置?
解决方案
推荐阅读
- reactjs - 如何使用 useState 制作一个自定义钩子,如果状态改变,它可以更新多个元素?
- c# - 无法在我的 C#.NET Winforms 应用程序中使用 DYMO 280 标签打印机
- kotlin-exposed - 如何在 Kotlin Exposed 中应用“NOW()”作为日期时间列值?
- python - 如何将包含数据和 datetime64[ns] 的列表与具有 datetime64[ns] 索引的 pandas 数据框合并
- c - 如何修复 GDB 的错误“指定给 RtlFreeHeap 的地址无效”
- jquery - 如何仅将数据表中选定的复选框 id 保存回数组中的控制器
- html - 如何在 IE11 中设置 Mailto 链接?
- oracle - 在plsql中将blob图像转换为PUBLIC.ORDIMAGE
- javascript - 简单待办事项列表:当列表为空时添加“无”,或在添加至少一项时将其删除。更好的解决方案是什么?
- sql - 在将 oracle 查询转换为大查询时出现“语法错误:预期的“(”或关键字 UNNEST 但得到标识符...”