Make Changes To sw-precache service-worker

614 views Asked by At

I am using sw-precache and I understand that in order to edit the service-worker.js file I need to do this (as detailed in the service-worker.js file)

// This file should be overwritten as part of your build process. // If you need to extend the behavior of the generated service worker, the best approach is to write // additional code and include it using the importScripts option: // https://github.com/GoogleChrome/sw-precache#importscripts-arraystring

but I do not know where to add the importscripts() code. Does it go in the service-worker.js file? Surely that gets over-ridden on each project build.

2

There are 2 answers

0
SSED On

Add it to the sw-precache-config.js file.

Good example here: Rewrite URL offline when using a service worker

0
Michael Schober On

Just include it like so:

importScripts: ['custom-offline-import.js']

Here is an example with an config including the importScripts config option at the end:

var packageJson = require('../package.json');
var swPrecache = require('../lib/sw-precache.js');
var path = require('path');

function writeServiceWorkerFile(rootDir, handleFetch, callback) {

  var config = {
    cacheId: packageJson.name,
    runtimeCaching: [{
      // See https://github.com/GoogleChrome/sw-toolbox#methods
      urlPattern: /runtime-caching/,
      handler: 'cacheFirst'
    }],
    staticFileGlobs: [rootDir + '/**/*.{js,html,css,png,jpg,gif}'],
    stripPrefix: rootDir,
    importScripts: ['custom-offline-import.js']
  };

  swPrecache.write(path.join(rootDir, 'service-worker.js'), config, callback);
}

Hope I could help you!