Reactjs 如何在create react应用程序的web worker中导入已安装的节点模块?
我使用createreact应用程序创建了一个简单的React应用程序。 我在Reactjs 如何在create react应用程序的web worker中导入已安装的节点模块?,reactjs,webpack,node-modules,create-react-app,web-worker,Reactjs,Webpack,Node Modules,Create React App,Web Worker,我使用createreact应用程序创建了一个简单的React应用程序。 我在public文件夹中添加了这个简单的worker.js: importScripts("fuse.js"); const searchHandler = () => { console.log(this.location.pathname); return "Imported Module!"; }; onmessage = (e) => { cons
public
文件夹中添加了这个简单的worker.js
:
importScripts("fuse.js");
const searchHandler = () => {
console.log(this.location.pathname);
return "Imported Module!";
};
onmessage = (e) => {
const startTime = new Date().getTime();
const workerResults = searchHandler();
postMessage({
workerResults,
time: new Date().getTime() - startTime
});
};
在我的App.js
中,我调用worker.js
:
import React from "react";
import ReactDOM from "react-dom";
function App() {
const worker = new window.Worker(process.env.PUBLIC_URL + "/worker.js");
worker.postMessage({});
worker.onmessage = (e) => {
const { workerResults, time } = e.data;
console.log({ workerResults, time });
};
return (
<div>The App!
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
注:
fuse.js
已安装,我可以成功导入并使用它
直接在App.js
中下面的错误消息说明一切正常。如果您在浏览器中打开以下地址
http://localhost:3000/fuse.js
,它会给您一个找不到的错误。因此webWorker无法导入脚本。
worker.js:1 Uncaught DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:3000/fuse.js' failed to load.
at http://localhost:3000/worker.js:1:1