Daniel Dróżdzel
Daniel Dróżdzel

Reputation: 65

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

Upvotes: 0

Views: 1041

Answers (2)

Aashish Singla
Aashish Singla

Reputation: 53

Well, after playing around with the url pattern, i realised that this is where I had erred. One fix, in the URL pattern and i saw indexeddb queue getting created and background sync starting to happen as expected. Thanks a lot

Upvotes: 0

Jeff Posnick
Jeff Posnick

Reputation: 56044

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,
      },
    },
  },
}]

Upvotes: 2

Related Questions