How to create Web Worker in a SvelteKit app on Vercel?

Viewed 1510

I've created a SvelteKit webapp that works great on my desktop in my local environment. I launch the browser/webserver with:

npm run dev -- --open

Now I've just deployed to Vercel. Everything works great, except the JavaScript command I use to launch my Web Worker gives a 404 error in the browser console:

new Worker('./lib/game/runs_thread.js')

Sure enough, if I copy /lib/game/runs_thread.js into my browser after my domain name, I get a 404 error. Where is my runs_thread.js and how can I launch my Worker?

2 Answers

I think what you need to do is replace

new Worker('./lib/game/runs_thread.js')

with

import workerURL from './lib/game/runs_thread.js?url';
//...
new Worker(workerURL)

Alternatively,

import MyWorker from "./path/to/worker.js?worker"
new MyWorker()

From vite's documentation

Related