I have a workspace in react where I am trying to setup service workers.
in main.tsx I do :
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
serviceWorkerRegistration.register({
onSuccess: () => pwaStore.setState((state) => ({ ...state, isReady: true })),
onUpdate: () => pwaStore.setState((state) => ({ ...state, hasUpdate: true })),
});
serviceWorker.js is the same as the default one from pwa-template, I just changed this line to work with NX.
const swUrl = `${process.env.NX_PUBLIC_URL}/service-worker.js`;
registerValidSW(swUrl, config);
service-worker.js is the default one and contains some imports
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
Now, when I deploy and run this project, I am prompted with
Error during service worker registration: DOMException: Failed to register a ServiceWorker for scope ('xxx') with script ('xxx/service-worker.js'): The script has an unsupported MIME type ('text/html').
So, I guess the service-worker is not found when loading from direct url. So I added it on the build
"assets": [
"apps/core/src/service-worker.js",
"apps/core/src/manifest.json",
"apps/core/src/robots.txt",
"apps/core/src/favicon.ico",
"apps/core/src/assets"
],
and now, it does find it, but I get prompted with
Uncaught SyntaxError: Cannot use import statement outside a module (at service-worker.js:1:1)
I am unsure on how to fix this now.