5

I know that we can test our service worker in production mode, but the proccess of re-building and deploying is quite annoying. Is there some way to enable serive worker in dev mode?

1 Answer 1

2

Change this

window.addEventListener('load', () => {

      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;


      console.log("file location" + swUrl);
      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(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit'
          );
        });
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl, config);
      }
    });

with this

window.addEventListener('load', () => {

      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

      console.log("file location" + swUrl);

        // Is not localhost. Just register service worker
        registerValidSW(swUrl, config);

    });

in your serviceWorker.js file

also put replace this

if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator ) {

with this

if ( 'serviceWorker' in navigator ) {

notice its checking for prod so removing that condition will start service worker on local also

Sign up to request clarification or add additional context in comments.

3 Comments

It worked but it didn't cache the static file like in production mode. I don't think service-worker.js exists in dev mode
All this will become tricky with default service worker. Will suggest you to right your own service worker either vanilla or with workbox.
My problem is that the server does not return the service worker: http://localhost:3000/service-worker.js return the index.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.