comlink-everywhere
v0.2.7
Published
This is a workaround to help patch inconsistent environments until module workers (and eventually [module block](https://github.com/tc39/proposal-js-module-blocks) workers) are available everywhere. Module workers are:
Downloads
18
Readme
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), anddeno
. - 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
, thetype
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 importingnode
modules unless necessary), which means it is not available synchronously.
- The implementation uses a dynamic import to get the
.terminate()
is not currently available onnode
workers. Please file an issue if you want to use this library and be able to call.terminate()
.- Note that we always call
.unref()
fornode
workers, which means they will not hold up program exit.
- Note that we always call