简体   繁体   中英

How can I allow imports into my webworker?

I have some basic code here.

https://codesandbox.io/s/competent-nightingale-80r4ps?file=/src/App.js:24-332

App.js : I create a webworker, and I have a function to post a message to that worker. When I receive a message back, I run console.log(e.data); .

export default function App() {
  const worker = new Worker("Worker.js");

  worker.onmessage = (e) => {
    console.log(e.data);
  };

  function getCount() {
    worker.postMessage("get count");
  }
  return (
    <div className="App">
      <button onClick={getCount}>Get count!</button>
    </div>
  );
}

Worker.js : Inside the worker, I create a counter object and post a message with its value.

class counter {
  constructor() {
    this.value = Math.floor(Math.random() * 100);
  }
}

onmessage = (e) => {
  const myCounter = new counter();
  this.postMessage(myCounter.value);
};

I would like to import the below helper functions and classes into my webworker, instead of embedding them in the file directly. Is there a way to do this if my worker is located in public ?

My file structure is like this:

root
-src
--utility1
--class1
-public
--webworker

Workers can have type classic or module . Workers with type module support ES6 modules.

Example: index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Module Worker Example</title>
  </head>
  <body>
    <script src="index.js"></script>
  </body>
</html>

index.js

const worker = new Worker('Worker.js', { type: 'module' });

worker.onmessage = (e) => {
  console.log(e.data);
};

function getCount() {
  worker.postMessage('get count');
}

getCount();

Worker.js

import { Counter } from './Counter.js';

onmessage = (e) => {
  const myCounter = new Counter();
  postMessage(myCounter.value);
};

Counter.js

export class Counter {
  constructor() {
    this.value = Math.floor(Math.random() * 100);
  }
}

Currently, it's not supported by all major browsers.

An alternative option is a worker with type classic and importScripts :

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Module Worker Example</title>
  </head>
  <body>
    <script src="index.js"></script>
  </body>
</html>

index.js

const worker = new Worker('Worker.js');

worker.onmessage = (e) => {
  console.log(e.data);
};

function getCount() {
  worker.postMessage('get count');
}

getCount();

Worker.js

importScripts('./Counter.js');

onmessage = (e) => {
  const myCounter = new Counter();
  postMessage(myCounter.value);
};

Counter.js

class Counter {
  constructor() {
    this.value = Math.floor(Math.random() * 100);
  }
}

It works on all major browsers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM