javascript - 当我在 JS worker 中导入 WASM 时,“无法解析模块说明符”或“未定义窗口”
问题描述
我正在尝试在 JS 工作者中导入我的 WASM 库(用 Rust 编写)。我得到了错误:
Uncaught (in promise) TypeError: Failed to resolve module specifier 'mylib'
或者如果我尝试使用worker-loader
错误是不同的,但在同一行:
window is not defined
错误的性质是什么,我应该如何修复它?
详情如下所示。我试图使示例尽可能少(不带worker-loader
)。
我的项目结构是:
wasm-worker-example/
mylib/
pkg/*
src/
lib.rs
Cargo.toml
www/
bundles/*
node_modules/*
index.html
index.js
my.worker.js
package.js
webpack.config.js
库文件
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn concat(a: &str, b: &str) -> String {
a.to_string() + b
}
货运.toml
[package]
name = "mylib"
version = "0.1.0"
authors = ["Alexander <mail@fomalhaut.su>"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
包.json
{
"name": "www",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"mylib": "file:../mylib/pkg",
"@babel/core": "^7.9.6",
"babel-loader": "^8.1.0",
"webpack": "^4.43.0",
"webpack-bundle-tracker": "^1.0.0-alpha.1",
"webpack-cli": "^3.3.11"
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
mode: 'development',
context: __dirname,
entry: './index',
output: {
path: path.resolve('./bundles/'),
filename: 'app.js',
publicPath: "/bundles/"
},
plugins: [
new BundleTracker({filename: './webpack-stats.json'}),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
],
},
};
索引.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="bundles/app.js"></script>
</head>
<body>
</body>
</html>
index.js
import("mylib").then(wasm => {
// It works fine
console.log(wasm.concat("qwe", "rty"));
var worker = new Worker("my.worker.js");
worker.postMessage('Message to worker');
});
我的.worker.js
// Error: Uncaught (in promise) TypeError: Failed to resolve module specifier 'mylib'
import("mylib").then(wasm => {
// Not reached
console.log(wasm.concat("qwe", "rty"));
self.addEventListener('message', e => {
console.log(e.data);
});
});
我准备mylib
(在mylib
):
wasm-pack build
对于前端(在www
):
npm install
./node_modules/.bin/webpack
运行(在www
):
http-server
解决方案
推荐阅读
- python - 数组 tkinter 条目到标签
- c# - 当我从 SSRS 报告中保存 PDF 时,文本在保存的 PDF 中被重叠或截断
- java-native-interface - 从 cocos2d-x 到 Android 调用 JNI 在 Release 模式下不会触发
- c - 不带参数的 pthread_create 函数
- python - 在Python中首先是高度还是宽度?
- php - 如何从 php 容器中的 dockerfile 运行 composer install
- python - 加载由 tensorflow 训练的 Keras 模型时出错
- xamarin - 如何根据 Selected Bool 参数更改模板控件的属性 (TextColor)?
- asp.net - 通过 React Axios 使用具有相同路由的 Web API 服务
- javascript - 使用 vanilla javascript 上传 doc 或 excel 文件并在 html 页面上显示时显示垃圾字符