Search code examples
node.jsservice-workercreate-react-appprogressive-web-appsworkbox

How to add background-sync-plugin to workbox-build


I've got question regarding workbox and create-react-app v2. I'm using workbox-build to generate custom service worker, and there is a problem with injecting

const backgroundSync = new workbox.backgroundSync.Plugin('ticketsQueue', {
  maxRetentionTime: 24 * 60 // Retry for max of 24 Hours
});


const buildSW = () =>
  workboxBuild.generateSW({
    globDirectory: 'build',
   // importWorkboxFrom: 'local',
    globPatterns: ['**/*.{json,ico,html,js,css,woff2,woff,png,svg}'],
    globIgnores: ['asset-manifest.json'],
    skipWaiting: true,
    clientsClaim: true,
    swDest: 'build/sw.js',
    navigateFallback: 'index.html',
    directoryIndex: 'index.html',
    runtimeCaching: [
      {
        urlPattern: new RegExp(`^${apiUrl}/tickets/create`),
        handler: 'networkOnly',
        options: {
          plugins: [
            backgroundSync
          ]
        },
        method: 'POST'
      },
     ]
  });

buildSW();

When I try too execute buildSW() with nodejs it gives a reference error. ReferenceError: workbox is not defined How to include it? Or is there any other way? Thanks


Solution

  • There are a couple of options.

    First, you can switch to using injectManifest mode, and have complete control over your service worker, relying on the build tool to just inject the array of files to precache.

    Second, there is a shortcut options property that simplifies adding in the background sync plugin. The config looks something like:

    runtimeCaching: [{
      // Match any same-origin request that contains 'api'.
      urlPattern: /api/,
      handler: 'networkOnly',
      options: {
        backgroundSync: {
          name: 'my-queue-name',
          options: {
            maxRetentionTime: 60 * 60,
          },
        },
      },
    }]