Use web-worker for cross-platform Worker support
mainThe web-worker package provides a unified, web-compatible Worker implementation that works identically in both the browser and Node.js.
- In Node.js: It implements the Web Worker API on top of Node's
worker_threads. - In the browser: It acts as an alias for the native
WorkerAPI.
This allows you to write worker code once and publish it as an npm module that runs in any environment. It emulates browser-style WorkerGlobalScope within the worker and supports DOM-style events (Event.data, Event.type, etc.) and event handler properties (worker.onmessage = ...).
import Worker from 'web-worker';
const worker = new Worker('data:,postMessage("hello")');
worker.onmessage = e => console.log(e.data); // "hello"