0

I have a build folder which is generated via webpack, any idea how i can cache the entire folder, i tried the following but to no avail

self.addEventListener('install', e => {
    e.waitUntil(
        caches.open('notes').then(cache => {
            return cache.addAll([
            './build/*',
        ])
        .then(() => self.skipWaiting());
    }))
});

self.addEventListener('activate',  event => {
    event.waitUntil(self.clients.claim());
});

self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request).then(response => {
            return response || fetch(event.request);
        })
    );
});

Any help on how i can cache the entire build folders' file. I am not using the webpack plugin, just written my on SW.

Nitish Phanse
  • 552
  • 1
  • 9
  • 16

1 Answers1

2

cache.addAll() takes as its parameter an array of URLs. './build/*' isn't an array of URLs, and that sort of wildcard pattern has no meaning when run inside of a service worker on users' browsers.

What you really want to do use a wildcard pattern that gets evaluated at build time, locally on the same machine that's performing your Webpack build, which will have access to the local files in your build/ directory and can generate a full list of them. You need to express that intent within your Webpack build process, not within the cache.addAll() run from your service worker.

There are a few Webpack plugins, like sw-precache-webpack-plugin and offline-plugin, that automate the process of expanding wildcards at build time and injecting the resulting list of files (along with versioning information, which is also super-important) into a service worker file, which in turn gets run in your users' browsers. You mention that you don't want to use a plugin and instead write your own service worker, but I'd recommend at least looking at the source for those plugins (or for the sw-precache project) since you're almost certainly going to end up following a similar approach.

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167