Caching webpack hashed urls in a service worker

Viewed 1017

I am playing around with service workers. I currently have the following service worker:

const CACHE_NAME = 'my-site-cache-v1';
const urlsToCache = [
    'index.html',
    'app.bundle.js',
    'images/image.jpg'
];

self.addEventListener('install', function(event) {
    console.log("install");
    // Perform install steps
    event.waitUntil(
        caches.open(CACHE_NAME).then(function(cache) {
            console.log('Opened cache');
            return cache.addAll(urlsToCache);
        })
    );
});

However I use webpack to add a hash to all the files when building. This means I do not know which urls to cache in the service worker.

I am not sure how to get around this.

1 Answers

One way to accomplish this is to use plugins to tap into either the compilation or the final stats object and then programmatically create a service worker script you can add to the output.

Plugins commonly register a handler for either the emit or done events to accomplish this. At these points, you will be able to enumerate the assets being emitted, their URI and source file dependencies.

I would recommend perhaps looking into Workbox, since it's purpose is to integrate with the service worker API, more specifically the workbox-webpack-plugin, because it utilizes webpack's compiler to dynamically create the service worker script. html-webpack-plugin is also a useful source of information, since it's quite popular and most of us can understand what it needs to perform.

Related