How to bundle WebWorker coded with TypeScript in npm package

Note that this is specific to webpack 4. To use Web Workers in webpack 5, see https://webpack.js.org/guides/web-workers/.

Introduction

$ npx create-react-app demo  --template typescript 
$ cd demo/
$ npm install
$ npm install @dannadori/bodypix-worker-js
$ cp node_modules/\@dannadori/bodypix-worker-js/dist/bodypix-worker-worker.js public/ # <- Here!! Too lame!!

Premise

Bundle a file created with a js file

$ npm install -D worker-loader
rules: [
{ test: /\.ts$/, loader: 'ts-loader' },
{
test: /worker\.js$/i,
loader: "worker-loader",
options: {
inline:"no-fallback"
},
},
],
onmessage = function (event) {
setTimeout(() => {
postMessage(`[WORKER_JS] Waited ${event.data}ms`);
}, event.data)
};
import libJs from '../src-worker/worker.js'export class WebWorkerLibJs{
worker:Worker
constructor(){
this.worker = libJs()
this.worker.onmessage = (mess) =>{
console.log(`[WebWorkerLibJs] ${mess.data}`)
}
}
sendMessage = () =>{
this.worker.postMessage(2 * 1000);
}
}

Bundle a file created with a ts file

$ npm install -D worker-loader
rules: [
{ test: /\.ts$/, loader: 'ts-loader' },
],
declare module "worker-loader!*" {
class WebpackWorker extends Worker {
constructor();
}
export default WebpackWorker;
}
const ctx: Worker = self as any;

onmessage = async (event) => {
setTimeout(() => {
ctx.postMessage(`[WORKER_TS] Waited ${event.data}ms`);
}, event.data)

}
import libTs from "worker-loader?inline=no-fallback!./worker.ts";

export class WebWorkerLibTs{
worker:Worker
constructor(){
this.worker = new libTs()
this.worker.onmessage = (mess) =>{
console.log(`[WebWorkerLibTs] ${mess.data}`)
}
}

sendMessage = () =>{
this.worker.postMessage(3 * 1000);
}
}

Repository

I am very thirsty!!

Reference

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store