4

I am using Vite to build an SPA with React (typescript), and I am trying to register a service-worker. I am registering the script as type module, and service-worker.ts sits at src/web-worker/service-worker.ts. There is also a tsconfig.json at src/web-worker

Everything works in Dev, but when it's built, src/web-worker/service-worker.ts is not replaced with anything equivalent.

Any suggestions?

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="/src/styles/globals.css">
  <title>Vite App</title>
</head>

<body>
  <div id="root"></div>
  <script type="module" src="/src/main.tsx"></script>
  <script type="text/javascript">
    if ('serviceWorker' in navigator) {
      (async () => {
        await navigator.serviceWorker.register("src/web-worker/service-worker.ts", { type: 'module' })
        console.log("Service worker registered")
      })()
    }
  </script>
</body>

</html>

src/web-worker/service-worker.ts

// Constants
const CACHE_NAME = 'mycache-v1.0.0'
const urlsToCache = ['/']

declare const self: ServiceWorkerGlobalScope;

self.addEventListener('install', async (event: ExtendableEvent) => {
    try {
        // Create (open) cache
        const cache = await caches.open(CACHE_NAME)
        await cache.addAll(urlsToCache)
        console.log("Cache opened")
    } catch (err: any) {
        console.log("Error while installing SW: ", err.message)
    }
})

self.addEventListener('fetch', (e: FetchEvent) => {
    e.respondWith((async () => {
        // Handling fetch
        console.log(`Handling req for '${e.request.url}'`)
        const cachedRes = await caches.match(e.request, { cacheName: CACHE_NAME })
        if (cachedRes) {
            console.log(`Serving cached response for '${e.request.url}'`)
        }
        return cachedRes || await fetch(e.request)
    })())
})

export default null

src/web-worker/tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["ESNext", "WebWorker"],
    "allowJs": false,
    "skipLibCheck": false,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
  },
  "include": ["*.ts"]
}
1
  • 1
    You can try to register service worker with .js extension, and build with tsc before (or concurrent) dev and build scripts. There may be a Vite plugin that solves this problem, but I haven't found one yet. Commented Nov 18, 2021 at 2:51

1 Answer 1

5

There is a vitejs plugin for this https://github.com/antfu/vite-plugin-pwa. You can find the react documentation here https://vite-plugin-pwa.netlify.app/examples/react.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.