尝试使用worker-loader创建 SharedWorker 它没有创建它,只是创建了 Worker。似乎它忽略了选项。
父代码中的用法
import SharedWorker from "worker-loader!./workers/get-nth-fibonacci-number.shared-worker.js";
import "./styles/style.scss";
const btn = document.getElementById("calc-btn");
const input = document.getElementById("nth-input");
const result = document.getElementById("result-el");
const worker = new SharedWorker();
console.log("worker", worker);
worker.port.addEventListener("message", (e) => {
result.innerHTML = e.data;
});
worker.port.addEventListener("error", (e) => {
result.innerHTML = `message: ${e.message}; filename: ${e.filename}; line: ${e.lineno}`;
console.error(e);
});
//...
工人代码
import { getNthFobonacciNumber } from "../helpers/get-nth-fibonacci-number.js";
console.log("hello from worker");
self.addEventListener("connect", function (e) {
const port = e.ports[0];
console.log("port", port);
port.addEventListener("message", function (e) {
const num = e.data;
if (Number.isInteger(parseInt(num))) {
const result = getNthFobonacciNumber(num);
port.postMessage({ result, port });
} else {
throw new Error("Is not a number");
}
});
port.start();
});
webpack 规则
{
test: /\.shared-worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
worker: "SharedWorker",
},
},
但在控制台中,它显示为 Worker 类。它有什么问题?
依赖关系
"@babel/core": "^7.7.7",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/preset-env": "^7.7.7",
"babel-loader": "^8.0.6",
"brotli-webpack-plugin": "^1.1.0",
"clean-webpack-plugin": "^3.0.0",
"compression-webpack-plugin": "^3.0.1",
"css-loader": "^3.4.1",
"cssnano": "^4.1.0",
"file-loader": "^5.0.2",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.13.0",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"postcss-loader": "^3.0.0",
"postcss-preset-env": "^6.7.0",
"purgecss-webpack-plugin": "^1.6.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.1.2",
"terser-webpack-plugin": "^2.3.1",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1",
"worker-loader": "^3.0.5"
这件事要求我添加更多细节:“看起来你的帖子主要是代码;请添加更多细节。” 这只是一个存根文本。对不起。