Skip to content
Advertisement

React.js builds with Vite does not include service-worker.ts

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"]
}

Advertisement

Answer

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

Advertisement