Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 737
Ben Avatar asked Oct 30 '22 21:10

Ben


1 Answers

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.

like image 193
Hari krishna Avatar answered Jan 02 '23 20:01

Hari krishna