Reputation: 65
Inside my main file, I have
const loadWorker = async () => {
const SyncWorker = await import("$lib/canvas.worker?worker");
syncWorker = new SyncWorker.default();
syncWorker?.postMessage({});
};
Then in my unmount I have
onMount(() => {
console.log("Canvas: mounted");
loadWorker();
});
Then in my canvas.worker.ts file, I have a simple
onmessage = () => {
console.log("Hello from the worker!");
};
export {};
This message prints successfully in Chrome, but in firefox all I get is
SyntaxError: import declarations may only appear at top level of a module
Is this because the worker is stored on my local system, and maybe there's a special flag to allow loading of system files as workers (as that seems it may be a security concern)? Firefox docs say that my browser should support workers.
Upvotes: 1
Views: 1142
Reputation: 1811
SvelteKit's Service Worker support in dev mode require a browser that supports modules as workers. I don't have any trouble with it working on Chromium-based browsers, but Firefox has lagged way behind on it. That is the reason I switched to Vivaldi.
Also, things may have changed since this question was asked, but SvelteKit allows you to create a service worker simply by placing it in src/service-worker.js
or src/service-worker.ts
. It will manage it for you. It is a bit slow to replace the old version when you make changes in development. But that might be at least partially the fault of the browser. I work around it by clearing site data manually because I'm impatient. Browsers should pull in new versions automatically in time.
Upvotes: 0
Reputation: 1
You can automate the build script with nodemon.
npm install -D nodemon
And add a new script like this in your package.json
"sw-dev": "nodemon --watch src --ext * --exec "npm run build && npm run preview""
This is only a workaround if you want to development on unsupported browsers, not a good solution. Otherwise just stick to chrome-based browsers.
Upvotes: 0
Reputation: 65
Well, I should've read the documentation better.
service workers only work in the production build, not in development. To test it locally, use vite preview
Or in my case, "npm run build && npm run preview" worked.
Upvotes: 2