Portable Web Workers for JavaScript runtimes.
Installation#
npm install @rcompat/workerpnpm add @rcompat/workeryarn add @rcompat/workerbun add @rcompat/workerUsage#
import Worker from "@rcompat/worker";
const worker = new Worker(new URL("./worker.js", import.meta.url), {
name: "example",
});
worker.addEventListener("message", event => {
console.log(event.data);
});
worker.postMessage("hello");The package exposes the Web Worker interface in browsers, Bun, Deno, and Node.
Node workers are bootstrapped with self, postMessage, onmessage, and the
standard event-target methods so the same module worker can run in every
supported runtime.
Workers are always ES modules. The optional second argument has the shared
WorkerOptions shape { name?: string; type?: "module" }; module mode is the
default, so type can normally be omitted.
The portable interface includes:
postMessage(message, transfer?)addEventListener()andremoveEventListener()onmessage,onmessageerror, andonerrorterminate()
The package also exports the type-only Worker, WorkerConstructor, and
WorkerOptions contracts from its root. It has no runtime subpath exports.
Worker scripts should use the Web Worker messaging API rather than
runtime-specific APIs such as Node's parentPort.