The code
The function is ordinary TypeScript. Nothing about it knows it will run in a Worker.
/** Deliberately slow: each extra unit of `n` roughly multiplies the work by 1.6. */
export function fibonacci(n: number): number {
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}The Worker file hands that function to defineWorker and exports the type of the result.
import { defineWorker } from 'easy-web-worker/defineWorker';
import { fibonacci } from './math';
const worker = defineWorker(() => ({ fibonacci }));
export type MathWorker = typeof worker;The main thread creates the worker from the file and gets a typed method back. Only the type is imported from the Worker file, so none of its code ends up in the main bundle.
import { createWorker } from 'easy-web-worker/createWorker';
import workerUrl from './math.worker?worker&url';
import type { MathWorker } from './math.worker';
/** Only the type of the worker is imported here; its code is loaded by the browser as a Worker. */
export const createMathWorker = () =>
createWorker<MathWorker>(workerUrl, {
workerOptions: { type: 'module' },
});