Ben
Ben

Reputation: 1535

How to append custom code to the generated service worker file

I'm using Webpack and swPrecache. swPrecache generates a service-worker.js file for me and I now want to append custom code to the generated file.

I created a Webpack plugin that appends the babel transformed code to the service-worker.js file, like so:

swPrecache.write(filePath, options, (function(err) {

  // If we want to append an additional file.
  if (options.appendFile) {
    var sync = fs.readFile(options.appendFile, (error, code) => {
      if (error) {
        throw error;
      }
      let transformed = babel.transform(code, options.babelConfig || {});
      fs.appendFile(filePath, transformed.code);
    });
  }

  callback(err);
}));

This however does not include the code to make require() work in the file i'm appending. I believe I need to use Webpack to generate the service-worker.js file but i'm unsure how to do that, possibly via a custom entry point?

Upvotes: 5

Views: 924

Answers (1)

Hari krishna
Hari krishna

Reputation: 156

To include your custom script into generated serviceWorker, recommended way is to use the importScripts option in sw-precache config.You can find more details here.

Upvotes: 2

Related Questions