Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Workbox file service-worker.js never got used in a cra-template-pwa template create-react-app app #9637

Closed
hongbo-miao opened this issue Sep 13, 2020 · 3 comments

Comments

@hongbo-miao
Copy link
Contributor

hongbo-miao commented Sep 13, 2020

Originally posted at Stack Overflow https://stackoverflow.com/questions/63868997/how-to-use-the-workbox-file-service-worker-js-correctly-in-a-cra-template-pwa-te

Here is the copy:


I tried to use create-react-app both 3.4.1 and 4.0.0-next.77 (the two apps got generated have no difference) to create a new PWA app by

    create-react-app my-app --template cra-template-pwa

The code is at https://github.com/Hongbo-Miao/react-4-js-wb-test

There are two files related with service worker / Workbox.

  • service-worker.js
  • serviceWorkerRegistration.js

Here is original service-worker.js:

    /* eslint-disable no-restricted-globals */
    
    // This service worker can be customized!
    // See https://developers.google.com/web/tools/workbox/modules
    // for the list of available Workbox modules, or add any other
    // code you'd like.
    // You can also remove this file if you'd prefer not to use a
    // service worker, and the Workbox build step will be skipped.
    
    import { clientsClaim } from 'workbox-core';
    import { ExpirationPlugin } from 'workbox-expiration';
    import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
    import { registerRoute } from 'workbox-routing';
    import { StaleWhileRevalidate } from 'workbox-strategies';
    
    clientsClaim();
    
    // Precache all of the assets generated by your build process.
    // Their URLs are injected into the manifest variable below.
    // This variable must be present somewhere in your service worker file,
    // even if you decide not to use precaching. See https://cra.link/PWA
    precacheAndRoute(self.__WB_MANIFEST);
    
    // Set up App Shell-style routing, so that all navigation requests
    // are fulfilled with your index.html shell. Learn more at
    // https://developers.google.com/web/fundamentals/architecture/app-shell
    const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
    registerRoute(
      // Return false to exempt requests from being fulfilled by index.html.
      ({ request, url }) => {
        // If this isn't a navigation, skip.
        if (request.mode !== 'navigate') {
          return false;
        } // If this is a URL that starts with /_, skip.
    
        if (url.pathname.startsWith('/_')) {
          return false;
        } // If this looks like a URL for a resource, because it contains // a file extension, skip.
    
        if (url.pathname.match(fileExtensionRegexp)) {
          return false;
        } // Return true to signal that we want to use the handler.
    
        return true;
      },
      createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
    );
    
    // An example runtime caching route for requests that aren't handled by the
    // precache, in this case same-origin .png requests like those from in public/
    registerRoute(
      // Add in any other file extensions or routing criteria as needed.
      ({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'), // Customize this strategy as needed, e.g., by changing to CacheFirst.
      new StaleWhileRevalidate({
        cacheName: 'images',
        plugins: [
          // Ensure that once this runtime cache reaches a maximum size the
          // least-recently used images are removed.
          new ExpirationPlugin({ maxEntries: 50 }),
        ],
      })
    );
    
    // This allows the web app to trigger skipWaiting via
    // registration.waiting.postMessage({type: 'SKIP_WAITING'})
    self.addEventListener('message', (event) => {
      if (event.data && event.data.type === 'SKIP_WAITING') {
        self.skipWaiting();
      }
    });
    
    // Any other custom service worker logic can go here.

Based on the comment inside and the official doc, I think I should be able to customize Workbox.

I turned on service worker in index.js by changing unregister() to register():

    import * as serviceWorkerRegistration from './serviceWorkerRegistration';
    serviceWorkerRegistration.register();

However, I cannot find any part of code using service-worker.js, so even I added

    console.log('Workbox got called in service-worker.js');

inside, the console.log never got called neither in dev environment

    yarn start

nor in prod environment

    yarn build
    serve build --ssl-cert ./my.crt --ssl-key ./my.ke

I tried to add

    import './service-worker';

on top of index.js

However, it will give me error

not-an-array: The parameter 'entries' passed into 'workbox-precaching.PrecacheController.addToCacheList()' must be an array.

Based on the error, if I change precacheAndRoute(self.__WB_MANIFEST); to precacheAndRoute([self.__WB_MANIFEST]);, the error becomes

add-to-cache-list-unexpected-type: An unexpected entry was passed to 'workbox-precaching.PrecacheController.addToCacheList()' The entry 'undefined' isn't supported. You must supply an array of strings with one or more characters, objects with a url property or Request objects.

How can I use the Workbox file service-worker.js correctly? Thanks


UPDATE:

I found even I remove src/service-worker.js, and yarn build again, it will still generate a build/service-worker.js (content copy below) which is not related with original src/service-worker.js at all.

    /**
     * Welcome to your Workbox-powered service worker!
     *
     * You'll need to register this file in your web app and you should
     * disable HTTP caching for this file too.
     *
     * The rest of the code is auto-generated. Please don't update this file
     * directly; instead, make changes to your Workbox build configuration
     * and re-run your build process.
     */
    
    importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
    
    importScripts(
      "/precache-manifest.e90b8a1c98bf449d45dd07f902f9c090.js"
    );
    
    self.addEventListener('message', (event) => {
      if (event.data && event.data.type === 'SKIP_WAITING') {
        self.skipWaiting();
      }
    });
    
    workbox.core.clientsClaim();
    
    /**
     * The workboxSW.precacheAndRoute() method efficiently caches and responds to
     * requests for URLs in the manifest.
     */
    self.__precacheManifest = [].concat(self.__precacheManifest || []);
    workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
    
    workbox.routing.registerNavigationRoute(workbox.precaching.getCacheKeyForURL("/index.html"), {
      
      blacklist: [/^\/_/,/\/[^/?]+\.[^/]+$/],
    });
@hongbo-miao hongbo-miao changed the title How to use the Workbox file service-worker.js correctly in a cra-template-pwa template create-react-app app? Workbox file service-worker.js never got used in a cra-template-pwa template create-react-app app Sep 13, 2020
@petetnt
Copy link
Contributor

petetnt commented Sep 14, 2020

@jeffposnick might have some insight on this

@jeffposnick
Copy link
Contributor

Things are a little messy now, with c-r-a v4 still in pre-release.

I'd recommend doing

npx create-react-app@next my-app --template cra-template-pwa

and then you should have a webpack config and templated files that will work together. If you start with that, you can then customize the src/service-worker.js file as you see fit, and yarn build will produce a final, compiled service worker.

You still need to go to index.js and switch the call in there to serviceWorkerRegistration.register(); before it will actually be registered and used.

(Thank you for the dependency update you submitted in cra-template/pwa#6. I just tested out the full flow, and with those additional dependencies, everything worked for me as expected.)

@hongbo-miao
Copy link
Contributor Author

Thank you so much @jeffposnick ! I will close for now and report back for what I found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants