Search code examples
npmsassvitesveltekitterser

Vite: This module can only be imported inside a service worker


After a pnpm package update, I can't start my SvelteKit project anymore. Something is messy with the tooling: pnpm, vite, sass, terser or sveltekit, I don't know.

> pnpm run dev
VITE v4.0.0  ready in 2880 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h to show help
...

This module can only be imported inside a service worker
    at $service-worker:3:8
    at instantiateModule (file:///Users/me/myapp/node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/vite/dist/node/chunks/dep-ed9cb113.js:53246:15)

This point out to this line (I have no clue what it does):

try {
   // eslint-disable-next-line @typescript-eslint/no-empty-function
   const AsyncFunction = async function () { }.constructor;
   const initModule = new AsyncFunction(`global`, ssrModuleExportsKey, ssrImportMetaKey, ssrImportKey, ssrDynamicImportKey, ssrExportAllKey, '"use strict";' + result.code + `\n//# sourceURL=${mod.url}`);
   await initModule(context.global, ssrModule, ssrImportMeta, ssrImport, ssrDynamicImport, ssrExportAll);  <---------- HERE
    }

Solution

  • For whatever reason (auto import in VsCode I guess), the following import was added in my code inside a +page.svelte file: import { prerendered } from "$service-worker";.

    Never used that but this was the source of evil. I which I could get the incriminated line and file in the VsCode terminal, or in the Chrome console ... If someone knows how this could happens, I'll take it 🙂