WorkboxSW constructor throws error Undefined

3.3k views Asked by At

In my service worker file, I am using this code:

importScripts("https://storage.googleapis.com/workbox-cdn/releases/3.0.0-beta.2/workbox-sw.js");
const workbox = new WorkboxSW();

But I am getting error Uncaught ReferenceError: WorkboxSW is not defined hence my service worker is not registering.

2

There are 2 answers

0
Jeff Posnick On

In Workbox v3, you won't normally explicitly construct a WorkboxSW instance. Instead, there's a workbox variable exposed in the global scope that provides the interface to the library.

Here's an example, excepted from the migration guide:

Previously in v2:

importScripts('<path to workbox-sw>/importScripts/workbox-sw.prod.v2.1.3.js');

const workbox = new WorkboxSW({
  skipWaiting: true,
  clientsClaim: true,
  // etc.
});

workbox.router.registerRoute(...);

In v3, you just have to import the workbox-sw.js script, and a ready-to-use instance will be automatically available in the global namespace as workbox:

importScripts('<path to workbox-sw>/3.0.0/workbox-sw.js');

// workbox is implicitly created and ready for use.
workbox.routing.registerRoute(...);
0
Adefowowe On

I faced a similar issue but in my case, my sw was registering despite the error message. Adding type="javascript/worker" like this: <script type="javascript/worker" src="sw.js"></script> at my entry point, removed the error in dev tools.