WASM ライブラリ (Rust で記述) を JS ワーカー内にインポートしようとしています。そして、私はエラーが発生します:
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
lib.rs
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',
      },
    ],
  },
};
index.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');
});
my.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