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
{
"pilerOptions": {
"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"]
}
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
{
"pilerOptions": {
"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"]
}
Share
Improve this question
asked Nov 14, 2021 at 9:27
Sohail SahaSohail Saha
5732 gold badges7 silver badges18 bronze badges
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. – Yuns Commented Nov 18, 2021 at 2:51
1 Answer
Reset to default 5There is a vitejs plugin for this https://github./antfu/vite-plugin-pwa. You can find the react documentation here https://vite-plugin-pwalify.app/examples/react.html