Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Last active December 20, 2022 10:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cecilemuller/96871556abfe01ddb36eacc0ea3d2cc3 to your computer and use it in GitHub Desktop.
Save cecilemuller/96871556abfe01ddb36eacc0ea3d2cc3 to your computer and use it in GitHub Desktop.
Typescript Webworker
/* eslint-env browser */
import type {IRequestWorker} from "./worker.ts";
const worker = new Worker(new URL("./worker.ts", import.meta.url)) as IRequestWorker;
// Receive from the worker
worker.onmessage = ({data: {myresponse}}) => {
console.log(myresponse);
};
// Send to the worker
worker.postMessage({myrequest: 111});
export {};
/* eslint-env worker */
type TRequest = {
myrequest: number;
};
type TResponse = {
myresponse: number;
};
export interface IRequestWorker {
postMessage: (message: TRequest) => void;
onmessage: (message: MessageEvent<TResponse>) => void;
}
interface IResponseWorker {
postMessage: (message: TResponse) => void;
onmessage: (message: MessageEvent<TRequest>) => void;
}
const worker: IResponseWorker = self as any;
// Receive from the main thread
worker.onmessage = ({data: {myrequest}}) => {
console.log(myrequest);
// Send to the main thread
worker.postMessage({myresponse: 222});
};
@cecilemuller
Copy link
Author

Using these types, you avoid the dom + webworker libs issue, yet still get Intellisense for worker messages.

The new URL("./worker.ts", import.meta.url) syntax is the way Webpack 5 automatically detects and extracts webworkers without a separated entry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment