How to make web workers with TypeScript and webpack

Using batressc’ answer I have managed to actually get passing messages back and forth working, in a somewhat nice manner.

Adding to his answer with the libs, the Typescript code also needs some nudges to get working.

First, create a file to make the file-loader cooperate with you when importing. I have a file named file-loader.d.ts with the following contents:

declare module "file-loader?name=[name].js!*" {
    const value: string;
    export = value;
}

Next, in your main.ts import the worker using the fileloader:

import * as workerPath from "file-loader?name=[name].js!./test.worker";

This workerPath can then be used to create the actual worker:

const worker = new Worker(workerPath);

Next, create the actual worker file, test.worker.ts, with the following content:

addEventListener('message', (message) => {
    console.log('in webworker', message);
    postMessage('this is the response ' + message.data);
});

You can then send messages back and forth in the main.ts file:

worker.addEventListener('message', message => {
    console.log(message);
});
worker.postMessage('this is a test message to the worker');

I have gathered everything in a github repository, if someone needs to the full perspective to get everything working: https://github.com/zlepper/typescript-webworker

This repository also have a webpack.config.js to show how webpack could be configured for this.

Leave a Comment