Search code examples
javascriptservice-workerworkbox

Service worker with workbox and Gulp, how to add my own rules?


I just started to work with workbox and I am using Gulp to generate my service worker with the following code in the example: https://developers.google.com/web/tools/workbox/get-started/gulp

It generates the service-worker file properly, but the thing I do not understand is how can I add my own code to the file? Lets say I want to add the following route:

workboxSW.router.registerRoute(
  'https://pixabay.com/get/(.*)',
  cacheOneWeekStrategy
);

Now if I run the gulp task again it overwrites my own route. How can I add my own code? I also want to add some event listeners etc.

Update: so far I have found out that I can use injectManifest() which will inject routes to the file inside workboxSW.precache([]); But I still need to copy the actual service worker script somehow.


Solution

  • I could not figure out any other way. This is my solution. I copy workbox from node_modules and then I write my code to sw.js and then I use inject-manifest to inject the routes to my own code.

    gulp.task('copy-workbox', () => {
      return gulp.src(['node_modules/workbox-sw/build/importScripts/workbox-sw.prod*.js'])
        .pipe(rename('workbox.js'))
        .pipe(gulp.dest('app'));
    });
    
    gulp.task('inject-manifest', () => {
      return wbBuild.injectManifest({
        swSrc: './app/sw.js',
        swDest: './app/service-worker.js',
        globDirectory: './app/',
        globPatterns: ['**\/*.{html,js,css,png}'],
        globIgnores: ['admin.html']
      })
      .then(() => {
        console.log('Service worker generated.');
      });
    });

    UPDATE: after some reading I figured out it is not a good idea to rename the workbox. However I couldn't find a way to do this otherwise.