2

我正在尝试制作一个网络工作者来防止停止 React 主线程。工人应该阅读图像并做各种事情。

该应用程序是使用create-react-app.

目前我有

webpack.config.js

module.exports = {
    module: {
        rules: [
            {
                test: /\.worker\.js$/,
                use: { loader: 'worker-loader' }
            }
        ]
    }
};

WebWorker.js

export default class WebWorker {
    constructor(worker) {
        const code = worker.toString();
        const blob = new Blob(['('+code+')()'], {type: "text/javascript"});
        return new Worker(URL.createObjectURL(blob),  {type: 'module'});
    }
}

readimage.worker.js

import Jimp from "jimp";

export default () => {
    self.addEventListener('message', e => { // eslint-disable-line no-restricted-globals
        if (!e) return;
        console.log('Worker reading pixels for url', e.data);
        let data = {};

        Jimp.read(e.data).then(image => {
            // jimp does stuff
            console.log('Worker Finished processing image');
        })

        postMessage(data);
    })
};

然后在我的 React 组件AppContent.js

import WebWorker from "./workers/WebWorker";
import readImageWorker from './workers/readimage.worker.js';

export default function AppContent() {
    const readWorker = new ReadImageWorker(readImageWorker);
    readWorker.addEventListener('message', event => {
        console.log('returned data', event.data);
        setState(data);
    });

    // callback that is executed onClick from a button component
    const readImageContents = (url) => {
        readWorker.postMessage(url);
        console.log('finished reading pixels');
    };
}

但是当我运行它时,我得到了错误

未捕获的 ReferenceError:未定义 jimp__WEBPACK_IMPORTED_MODULE_0__

如何正确地将模块导入网络工作者?

4

2 回答 2

1

您可能在 webpack 在 WebWorker 类中导入您的工作人员时遇到问题。尝试new Worker(URL.createObjectURL(blob), import.meta.url));像webpack 文档中记录的那样返回。

于 2022-01-28T11:22:54.547 回答
0

在我的 next.js 打字稿项目中,我使用此代码并在我的用例中回答:

  • function in onClick prop on the element at next.js
async () => {
  const testWorker = new Worker(
    new URL("./test.worker.ts", import.meta.url), {
      name: "test",
      type: "module",
    });
  testWorker.onmessage = function (event) {
    console.log("data:", event.data, "\n", "event:", event);
  };

  testWorker.postMessage([0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
}


  • test.worker.ts
self.onmessage = function ({ data }) {
  self.postMessage((data as number[]).map((d) => d * 10));
};

export {};
于 2022-02-07T20:46:00.603 回答