在 React 中创建 Web Worker [英] Creating a web worker inside React

查看:71
本文介绍了在 React 中创建 Web Worker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 create-react-app 创建的 React 应用程序,但没有弹出.我正在尝试使用网络工作者.我试过 worker-loader 包(https://github.com/webpack-contrib/worker-加载器).

I have a React app created with create-react-app, not ejected. I'm trying to use web workers. I've tried the worker-loader package (https://github.com/webpack-contrib/worker-loader).

如果我尝试开箱即用的 worker-loader(import Worker from 'worker-loader!../workers/myworker.js';),我会收到错误消息,告诉我 Webpack我已经知道 Create React App 不支持加载器.

If I try worker-loader out of the box (import Worker from 'worker-loader!../workers/myworker.js';), I get the error message telling me that Webpack loaders are not supported by Create React App, which I already know.

解决方案是弹出应用程序(我不想这样做)并编辑 webpack.config.js 还是有其他方法可以在 React 应用程序中使用网络工作者?

Would the solution be to eject the app (which I'd prefer not to do) and edit the webpack.config.js or is there some other way of using web workers inside a React app?

我在这里找到了解决方案:https://github.com/facebookincubator/create-react-app/issues/1277(由 yonatanmn 发布)

I have found the solution here: https://github.com/facebookincubator/create-react-app/issues/1277 (post by yonatanmn)

推荐答案

正如我在上述问题的 EDIT 中所写,我在这里找到了解决方案:https://github.com/facebookincubator/create-react-app/issues/1277

As I've written in the EDIT of my question above, I've found the solution here: https://github.com/facebookincubator/create-react-app/issues/1277

这是一个工作示例:

// worker.js
const 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的文件中:

Then, in the file that needs to use the 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆