1

我正在尝试在 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
4

0 回答 0