title: Webpack React Custom ServiceWorker EVERYTHING not defined
body: <p>I have attempted to add custom service workers to my Create React App project following this article:</p>
  <p><a href="https://medium.com/@chinmaya.cp/custom-service-worker-in-cra-create-react-app-3b401d24b875" rel="nofollow noreferrer">https://medium.com/@chinmaya.cp/custom-service-worker-in-cra-create-react-app-3b401d24b875</a></p>
  <p>However, when building I get a long stretch of errors from the <code>sw-custom.js</code> file where everything is not defined (See Image Below):</p>
  <p><a href="https://i.stack.imgur.com/SJsxv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SJsxv.png" alt="enter image description here" /></a></p>
  <p>Here are my files:</p>
  <p><code>react-build.js</code></p>
  <pre><code>const workboxBuild = require('workbox-build');
  
  const buildSW = () =&gt; {
    // The build is expected to fail if the
    // sw install rules couldn't be generated.
    // Add a catch block to handle this scenario.
    console.log('Building SW');
    return workboxBuild
      .injectManifest({
        swSrc: 'src/sw-custom.js', // custom sw rule
  
        swDest: 'build/sw.js', // sw output file (auto-generated
  
        globDirectory: 'build',
  
        globPatterns: ['**/*.{js,css,html,png,svg}'],
  
        maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
      })
      .then(({ count, size, warnings }) =&gt; {
        warnings.forEach(console.warn);
        console.info(`${count} files will be precached,
                    totaling ${size / (1024 * 1024)} MBs.`);
      });
  };
  
  buildSW();
  </code></pre>
  <p><code>sw-custom.js</code></p>
  <pre><code>if ('function' === typeof importScripts) {
    importScripts(
      'https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js'
    );
  
    // Global workbox
    if (workbox) {
      console.log('Workbox is loaded');
  
      // Disable logging
      workbox.setConfig({ debug: false });
  
      //`generateSW` and `generateSWString` provide the option
      // to force update an exiting service worker.
      // Since we're using `injectManifest` to build SW,
      // manually overriding the skipWaiting();
      self.addEventListener('install', (event) =&gt; {
        self.skipWaiting();
        window.location.reload();
        console.log('TESTTESTTEST');
      });
  
      // Manual injection point for manifest files.
      // All assets under build/ and 5MB sizes are precached.
      workbox.precaching.precacheAndRoute([]);
  
      // Font caching
      workbox.routing.registerRoute(
        new RegExp('https://fonts.(?:.googlepis|gstatic).com/(.*)'),
        workbox.strategies.cacheFirst({
          cacheName: 'googleapis',
          plugins: [
            new workbox.expiration.Plugin({
              maxEntries: 30,
            }),
          ],
        })
      );
  
      // Image caching
      workbox.routing.registerRoute(
        /\.(?:png|gif|jpg|jpeg|svg)$/,
        workbox.strategies.cacheFirst({
          cacheName: 'images',
          plugins: [
            new workbox.expiration.Plugin({
              maxEntries: 60,
              maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
            }),
          ],
        })
      );
  
      // JS, CSS caching
      workbox.routing.registerRoute(
        /\.(?:js|css)$/,
        workbox.strategies.staleWhileRevalidate({
          cacheName: 'static-resources',
          plugins: [
            new workbox.expiration.Plugin({
              maxEntries: 60,
              maxAgeSeconds: 20 * 24 * 60 * 60, // 20 Days
            }),
          ],
        })
      );
    } else {
      console.error('Workbox could not be loaded. No offline support');
    }
  }
  </code></pre>
  <p>CRA's <code>sw.js</code></p>
  <pre><code>// register() is not called by default.
  
  // This lets the app load faster on subsequent visits in production, and gives
  // it offline capabilities. However, it also means that developers (and users)
  // will only see deployed updates on subsequent visits to a page, after all the
  // existing tabs open on the page have been closed, since previously cached
  // resources are updated in the background.
  
  // To learn more about the benefits of this model and instructions on how to
  // opt-in, read [link removed to post on SO]
  // This optional code is used to register a service worker.
  // register() is not called by default.
  
  const isLocalhost = Boolean(
    window.location.hostname === 'localhost' ||
      // [::1] is the IPv6 localhost address.
      window.location.hostname === '[::1]' ||
      // 127.0.0.0/8 are considered localhost for IPv4.
      window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
      )
  );
  
  export function register(config) {
    if (process.env.NODE_ENV === 'production' &amp;&amp; 'serviceWorker' in navigator) {
      // The URL constructor is available in all browsers that support SW.
      const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
      if (publicUrl.origin !== window.location.origin) {
        // Our service worker won't work if PUBLIC_URL is on a different origin
        // from what our page is served on. This might happen if a CDN is used to
        // serve assets; see https://github.com/facebook/create-react-app/issues/2374
        return;
      }
  
      window.addEventListener('load', () =&gt; {
        const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
  
        if (isLocalhost) {
          // This is running on localhost. Let's check if a service worker still exists or not.
          checkValidServiceWorker(swUrl, config);
  
          // Add some additional logging to localhost, pointing developers to the
          // service worker/PWA documentation.
          navigator.serviceWorker.ready.then(() =&gt; {
            console.log(
              'This web app is being served cache-first by a service ' +
                'worker. To learn more, visit x'
            );
          });
        } else {
          // Is not localhost. Just register service worker
          registerValidSW(swUrl, config);
        }
      });
  
      askNotificationPerms();
    }
  }
  
  function registerValidSW(swUrl, config) {
    navigator.serviceWorker
      .register(swUrl)
      .then((registration) =&gt; {
        registration.onupdatefound = () =&gt; {
          const installingWorker = registration.installing;
          if (installingWorker == null) {
            return;
          }
          installingWorker.onstatechange = () =&gt; {
            if (installingWorker.state === 'installed') {
              if (navigator.serviceWorker.controller) {
                // At this point, the updated precached content has been fetched,
                // but the previous service worker will still serve the older
                // content until all client tabs are closed.
                console.log(
                  'New content is available and will be used when all ' +
                    'tabs for this page are closed. See x'
                );
  
                // Execute callback
                if (config &amp;&amp; config.onUpdate) {
                  config.onUpdate(registration);
                }
              } else {
                // At this point, everything has been precached.
                // It's the perfect time to display a
                // &quot;Content is cached for offline use.&quot; message.
                console.log('Content is cached for offline use.');
  
                // Execute callback
                if (config &amp;&amp; config.onSuccess) {
                  config.onSuccess(registration);
                }
              }
            }
          };
        };
      })
      .catch((error) =&gt; {
        console.error('Error during service worker registration:', error);
      });
  }
  
  function checkValidServiceWorker(swUrl, config) {
    // Check if the service worker can be found. If it can't reload the page.
    fetch(swUrl, {
      headers: { 'Service-Worker': 'script' },
    })
      .then((response) =&gt; {
        // Ensure service worker exists, and that we really are getting a JS file.
        const contentType = response.headers.get('content-type');
        if (
          response.status === 404 ||
          (contentType != null &amp;&amp; contentType.indexOf('javascript') === -1)
        ) {
          // No service worker found. Probably a different app. Reload the page.
          navigator.serviceWorker.ready.then((registration) =&gt; {
            registration.unregister().then(() =&gt; {
              window.location.reload();
            });
          });
        } else {
          // Service worker found. Proceed as normal.
          registerValidSW(swUrl, config);
        }
      })
      .catch(() =&gt; {
        console.log(
          'No internet connection found. App is running in offline mode.'
        );
      });
  }
  
  export function unregister() {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.ready
        .then((registration) =&gt; {
          registration.unregister();
        })
        .catch((error) =&gt; {
          console.error(error.message);
        });
    }
  }
  
  export function askNotificationPerms() {
    if ('PushManager' in window) {
      console.log('Push notifications are supported');
    }
  }
  </code></pre>
  <p>I'm guessing React is trying to compile the custom service worker file when it should just be used by <code>sw-build.js</code></p>
  <p>Help greatly appreciated :)</p>