I am using workbox-build to generate a service worker. My directory structure looks something like this:
src/
src/a.png
src/index.html
src/Workbox/
src/Workbox/workbox-window.prod.mjs
service-worker/
service-worker/build.js
build.js
, which I am running with Node.js, looks something like this:
const { generateSW } = require("workbox-build");
generateSW({
globDirectory: "../src/",
globPatterns: ["**/*"],
swDest: "../src/Workbox/service-worker.js",
})
The idea is that build.js
should generate a service worker, which is placed in src/Workbox
, that caches every file in src/
.
index.html
looks something like this:
<html>
<head>
<script type="module">
import { Workbox } from "./Workbox/workbox-window.prod.mjs";
if ("serviceWorker" in navigator) new Workbox("Workbox/service-worker.js").register();
</script>
</head>
<body></body>
</html>
However, upon loading the page, I get an error:
Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"http://localhost:8000/src/Workbox/a.png","status":404}]
The issue is clear: the service worker is trying to cache a nonexistent file src/Workbox/a.png
, rather than the file src/a.png
. I had expected only globDirectory
to be relevant to the cached file locations, but it seems swDest
is also relevant. If I change swDest
to "../src/service-worker.js"
and make the appropriate modification to index.html
, then all the files are precached as expected. But I would really like service-worker.js
to be placed in the src/Workbox
subdirectory rather than src/
. Is this possible?
In case anyone has the same issue in the future, this is not possible. The reason is that a service worker must be in the top scope due to scoping restrictions.