I have a simple Web Worker which executes a initiates and handles messages from a websocket. The logic for the handler is imported from another module "MessageHandler". The reason for this is that the websockets rely on an external dependency (stompjs) anyway, and I would like to keep a single module with the message hangling logic for browsers which don't support webworkers.
import { connect, destroy } from "../src/utilities/MessageHandler";
onmessage = (message) => {
const {type, value} = message.data;
switch (type?.toLowerCase()) {
case "connect":
connect(value, message => postMessage(message))
break;
case "destroy":
destroy();
break;
}
}
On the Dev server, this works fine, and I can place the file in the public folder, and start the Worker with:
if (typeof Worker !== "undefined") {
const workerUrl = new URL("/worker.js", import.meta.url);
const worker = new Worker(workerUrl, {type:"module"});
console.log(workerUrl);
worker.postMessage({type:"connect", value: {...channelInfo}},);
worker.onmessage = combineValues;
onUnmounted(() => {
worker.postMessage({type:"destroy"},);
worker.terminate();
})
} else {
console.log("Workers not allowed. Reverting to single threaded application.");
connect(channelInfo, combineValues)
onUnmounted(() => destroy())
}
However when I build for production, the import from MessageHandler is not compiled into the worker file, and the program fails to execute. Is there a way to configure vite to bundle this web worker properly without having to manually copy all of the dependencies into the file, and does the WW file have to remain in the public folder? Bonus points if there is a way to do it using typescript for the Worker file instead of being forced back to JS.