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

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

问题描述

我有一个用create-react-app创建的React应用,没有弹出。我正在尝试使用网络工作者。我已经尝试过worker-loader软件包( https://github.com/webpack-contrib/worker -loader )。

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(从'worker-loader导入Worker!.. /workers/myworker.js'; ),我收到一条错误消息,告诉我我已经知道,Create React App不支持Webpack加载器。

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应用程序中使用Web Worker的其他方法?

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)

推荐答案

正如我在上述问题的编辑中所写的那样,我在这里找到了解决方案: 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;

然后,在需要使用网络工作者的文件中:

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天全站免登陆