在React中创建一个Web Worker
我有一个用create-react-app创建的React应用,没有弹出。我正在尝试使用网络工作者。我已经尝试过worker-
loader软件包(https://github.com/webpack-contrib/worker-
loader)。
如果我尝试开箱即用(- import Worker from 'worker-
loader!../workers/myworker.js';)的worker-loader ,我将收到一条错误消息,告诉我Create React
App不支持Webpack加载器,我已经知道。
解决方案是弹出应用程序(我不希望这样做)并编辑webpack.config.js还是在React应用程序中使用Web Worker的其他方法?
编辑:我在这里找到解决方案:https : //github.com/facebookincubator/create-react-
app/issues/1277(由yonatanmn发布)
回答:
正如我在上面的问题的编辑中所写的那样,我在这里找到了解决方案:https : //github.com/facebookincubator/create-react-
app/issues/1277
这是一个工作示例:
// worker.jsconst workercode = () => {
self.onmessage = function(e) {
console.log('Message received from main script');
var workerResult = 'Received from main: ' + (e.data);
console.log('Posting message back to main script');
self.postMessage(workerResult);
}
};
let code = workercode.toString();
code = code.substring(code.indexOf("{")+1, code.lastIndexOf("}"));
const blob = new Blob([code], {type: "application/javascript"});
const worker_script = URL.createObjectURL(blob);
module.exports = worker_script;
然后,在需要使用Web Worker的文件中:
import worker_script from './worker';var myWorker = new Worker(worker_script);
myWorker.onmessage = (m) => {
console.log("msg from worker: ", m.data);
};
myWorker.postMessage('im from main');
以上是 在React中创建一个Web Worker 的全部内容, 来源链接: utcz.com/qa/430772.html