0.2.7 • Published 3 years ago

comlink-everywhere v0.2.7

Weekly downloads
-
License
(MIT OR GPL-3.0-o...
Repository
github
Last release
3 years ago

comlink-everywhere

This is a workaround to help patch inconsistent environments until module workers (and eventually module block workers) are available everywhere. Module workers are:

  • Available in Chromium-based browers, node (with an API significantly differing from all other environments), and deno.
  • Implemented in Safari, but probably not available on iOS until iOS 15.
  • In progress for Firefox

It also helps test bundler compat issues like snowpackjs/snowpack#3476

Usage

// index.js
import { workerFileConstructor, wrap } from "comlink-everywhere/outside";

(async () => {
  const Worker = await workerFileConstructor();
  const api = wrap(
    new Worker(new URL("./worker.js", import.meta.url), { type: "module" })
  );
  console.log(await api.add(3, 4));
})();
// worker.js
import { expose } from "comlink-everywhere/inside";

expose({
  add: (x, y) => x + y,
});

Construct from string

import { constructWorkerFromString } from "comlink-everywhere/outside";

(async () => {
  const worker = await constructWorkerFromString(
    // Note: this example only works in browsers.
    `self.postMessage("from worker");`
  );
  worker.addEventListener("message", (message) => console.log(message.data));
})();

For maximum compatibility in the short term, the best option is to compile the worker into a source string that does not use any imports, and does not use any syntax or functions specific to CommonJS (e.g. require()), ESM (e.g. import), or the web (e.g. importScripts())

Tradeoffs

  • If you're running node , the type option will be ignored and the worker will be instantiated as a classic/module worker matching the calling code. See https://github.com/nodejs/node/issues/30682
  • This library is written as ESM. It is only meant to be used with ESM, except specifically for workers instantiated from strings (as a workaround for Firefox and Safari's lack of module worker support).
  • The Worker constructor cannot be retrieved synchronously.
    • The implementation uses a dynamic import to get the node constructor for better compatibility (by not importing node modules unless necessary), which means it is not available synchronously.
  • .terminate() is not currently available on node workers. Please file an issue if you want to use this library and be able to call .terminate().
    • Note that we always call .unref() for node workers, which means they will not hold up program exit.
0.2.1

3 years ago

0.2.0

3 years ago

0.2.7

3 years ago

0.2.6

3 years ago

0.2.3

3 years ago

0.2.2

3 years ago

0.2.5

3 years ago

0.2.4

3 years ago

0.1.3

3 years ago

0.1.2

3 years ago

0.1.1

3 years ago

0.1.0

3 years ago