How to add webpack hash name to service worker file?

Viewed 585

I'm studying service worker for my app. This service worker cookbook(https://serviceworke.rs) is very helpful for me.

I'm configuring "Cache, update and refresh" strategy but can not know that how to add webpack hash name to service worker file.

For this, there is a few option, I know,

  1. Workbox (https://github.com/GoogleChrome/workbox)
  2. sw-precache (https://github.com/GoogleChromeLabs/sw-precache)
  3. sw-precache-webpack-plugin (https://github.com/goldhand/sw-precache-webpack-plugin#readme)

but I just want to make service worker file without plugin or 3rd tools AND put webpack chunkhash file name into my service worker file.

my-sw.js

var CACHE = 'cache-update-and-refresh';

self.addEventListener('install', function(evt) {
  console.log('The service worker is being installed.');
  evt.waitUntil(caches.open(CACHE).then(function (cache) {
    cache.addAll([
      './controlled.html',
      './asset',

      // here is problem. how to put this?
      /**
       main.72b835f75acd535f504c.js,
       vendor.d6b44fd0b72071c85ce2.js,
       aboutUs.d31139a7f363d5254560.js,
       ...etc...
      **/
    ]);
  }));
});

self.addEventListener('fetch', function(evt) {
  console.log('The service worker is serving the asset.');
  evt.respondWith(fromCache(evt.request));
  evt.waitUntil(
    update(evt.request)
    .then(refresh)
  );
});

function fromCache(request) {
  return caches.open(CACHE).then(function (cache) {
    return cache.match(request);
  });
}

function update(request) {
  return caches.open(CACHE).then(function (cache) {
    return fetch(request).then(function (response) {
      return cache.put(request, response.clone()).then(function () {
        return response;
      });
    });
  });
}

// Sends a message to the clients.
function refresh(response) {
  return self.clients.matchAll().then(function (clients) {
    clients.forEach(function (client) {
      var message = {
        type: 'refresh',
        url: response.url,
        eTag: response.headers.get('ETag')
      };
      client.postMessage(JSON.stringify(message));
    });
  });
}

0 Answers
Related