How to bundle WebWorker coded with TypeScript in npm package

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

--

--

--

Software researcher and engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

7 Problems you can avoid by using Nuxt.js for your next Vue app

JavaScript Object’s Property Accessors

Debugging made easy with new debugging APIs in Angular 9

Better way to listen chat reply box in JavaScript

Chaining Asynchronous Chores Synchronously

WW Maker Bytes | Issue 133

An Adventure with GraphQL and Relay, Part 2

The for…of Loop

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
dannadori

dannadori

Software researcher and engineer

More from Medium

Using NanoSQL + IndexedDB for Fast Vue Mockups

NODE JS, NPM, ADVANTAGES AND WHY IT IS SO POPULAR?

Update all node dependencies to their latest version without updating one by one

NextJS Link vs useRouter in Navigating.