I am trying to test using web workers in a Vite app, and when I run npm run dev it works as intended, but when I use npm run build and then use http-server in the dist folder, I get the error: "GET /workers/test.worker.ts" Error (404): "Not found"
My Vite app is the generic starter template with these sole additions:
@/stores/counter.ts
/* ... Inside Default Pinia Store ... */
function webworkerTest() {
console.log("this is a test message, wahoo!!");
const workerPath = "../workers/test.worker.ts";
const worker = new Worker(new URL(workerPath, import.meta.url), {
type: "module",
});
// Note the same setup as the Vite docs, although without {type: "module"} the console
// throws "404 (Not Found)" -from build- or "Unexpected token 'export'" -from dev-
console.log(workerPath, worker);
worker.addEventListener("message", (message) => {
console.log(message);
});
worker.postMessage("this is a test message to the worker");
}
/* ... Insert webworkerTest into Default Pinia Store return statement ... */
@/workers/test.worker.ts
console.log("hello from a webworker");
addEventListener("message", (message) => {
console.log("in webworker", message);
postMessage("this is the response " + message.data);
});
// To avoid --isolatedModules error
export {};
@/components/HelloWorld.vue
<script setup lang="ts">
import { useCounterStore } from "@/stores/counter";
const counterStore = useCounterStore();
counterStore.webworkerTest(); // Activate the test worker
defineProps<{
msg: string;
}>();
</script>
Vite Options:
- Vue 3
- TypeScript
- Pinia
- ESLint
- Prettier
Sources:
- Vite Docs
- MDN Web Worker Docs
- TypeScript Web Worker Example
- How do I compile web workers with vue3+vite? - Stack Overflow
Notes:
- I am fairly new to TypeScript and its various config options, although I have experience with C++ and JS
- I am using Composition API both in the Pinia store and the Vue SFCs
- I have even played around with the location of the
test.worker.tsfile, without any progress
Update:
I have experimented with the other option, Import with Query Suffixes, and it works in both dev and build, but I don't know how or why it works and I'm not sure what to search for in order to learn more, so I made a separate post here to try and get some insight.