How To Add Service Worker In React Project

create-react-app service worker not working
react service worker push notification
react native service worker
redux service worker
create react app with workbox
create-react-app web worker
create-react app cache
service worker tutorial

I want to add service worker in my react project. Project is ready the default Service seems not to works.

Even When I try to import this, it gives this error:

Attempted import error: './registerServiceWorker' does not contain a default export (imported as 'registerServiceWorker').

Furthermore, how to add files to be cached in the default version serviceWorker file.

If I add my own custom serviceWorker file just like for no-react (framework) application, will it works for react case?

Currently I have these code in my index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';


import { BrowserRouter } from 'react-router-dom'

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>,
document.getElementById('root'));

registerServiceWorker();

And in this says : " Attempted import error: './registerServiceWorker' does not contain a default export (imported as 'registerServiceWorker'). "

Service Worker which I am using is as under: (React's Default Code)

const isLocalhost = Boolean(
    window.location.hostname === 'localhost' ||
      // [::1] is the IPv6 localhost address.
      window.location.hostname === '[::1]' ||
      // 127.0.0.1/8 is 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' && '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

        return;
      }

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

  function registerValidSW(swUrl, config) {
    navigator.serviceWorker
      .register(swUrl)
      .then(registration => {
        registration.onupdatefound = () => {
          const installingWorker = registration.installing;
          if (installingWorker == null) {
            return;
          }
          installingWorker.onstatechange = () => {
            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  /CRA-PWA.'
                );

                // Execute callback
                if (config && config.onUpdate) {
                  config.onUpdate(registration);
                }
              } else {
                // At this point, everything has been precached.
                // It's the perfect time to display a
                // "Content is cached for offline use." message.
                console.log('Content is cached for offline use.');

                // Execute callback
                if (config && config.onSuccess) {
                  config.onSuccess(registration);
                }
              }
            }
          };
        };
      })
      .catch(error => {
        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)
      .then(response => {
        // 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 && contentType.indexOf('javascript') === -1)
        ) {
          // No service worker found. Probably a different app. Reload the page.
          navigator.serviceWorker.ready.then(registration => {
            registration.unregister().then(() => {
              window.location.reload();
            });
          });
        } else {
          // Service worker found. Proceed as normal.
          registerValidSW(swUrl, config);
        }
      })
      .catch(() => {
        console.log(
          'No internet connection found. App is running in offline mode.'
        );
      });
  }

  export function unregister() {
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.ready.then(registration => {
        registration.unregister();
      });
    }
  }

From your error information,there are something wrong with registerServiceWorker.js file.

import registerServiceWorker from './registerServiceWorker';

However,in registerServiceWorker.js file don't have the following

export registerServiceWorker

So, I recommend to add the below to registerServiceWorker.js

export default registerServiceWorker

Edit:

Use this to import js files

import * as registerServiceWorker from './registerServiceWorker';

And use it like this:

registerServiceWorker.unregister();

Edit2:

I think you have some misunderstanding about import/export.So I will explain it here.

If we want to import some file(e.g child.js) into another file(e.g parent.js).In the file like child.js,it must have export.

There are some ways to do so. 1. In Child.js

const child = () => {

}
export default Child

We will be able to import it in parent.js like below.With the default expression, we actually can use any name in the place of Child in the below.(Usually keep them the same.)

import Child from './child.js'
import ChildReplace from './child.js' //This also works, the ChildReplace are actually the Child in the child.js

  1. You may see another way to import.Like this:

    import * as registerServiceWorker from './registerServiceWorker';

The * means all the content in registerServiceWorker.js."as registerServiceWorker" are giving all the content a name for us to import them easily.

The way to import file because in the registerServiceWorker.js,there are many export expressions but without export default.

Making a Progressive Web App, unregister() to serviceWorker.register() will opt you in to using the service worker. #Why Opt-in? Offline-first Progressive Web Apps are faster  Now, if you start this application and run Audit after that, you will see service worker working and manifest file loaded. You can also run your app on your phone and see that “Add to home

you can import all the functions exported from registerServiceWorker.js file by using

import * as registerServiceWorker from './registerServiceWorker';

and after that you can call any method from that file to your index.js file like -

registerServiceWorker.unregister();

How to Make Your Existing React App Progressive in 10 Minutes , Now, let's try to run the app offline and see the PWA in action: In the development tools click on the application tab, select service workers in the left menu and check offline. Rename the service-worker part of it with anything else. I’m going to name mine service-worker-custom.js. Second, create a file inside of your public directory with the exact same name as the custom name you just came up with. So, I would create a file called service-worker-custom.js inside of the public directory. Now, inside of the service

Try this.

create-react-app FolderName

Is just auomatically creates a registerServiceWorker for your app

Custom Service Worker in CRA(Create React App), The create-react-app does provide a service worker out-of-the-box but only with limited capabilities i.e. precaching the assets under /build/static . You can find a number of pull-requests still under open/review state in the public CRA repository in order to enhance the in-built service worker. Note: This is not a primer on create-react-app or what a service worker is. This post assumes prior knowledge of both. So, I recently had the opportunity to work on a React project which involved

Progressive Web Apps with React.js: Part 3, To install a service worker, you need to register it in script. Registration informs the browser where your service worker is located and lets it  Also, service workers work on production mode only so make sure to build your application and serve it locally before testing your app for service workers. npm i http-server -D then add this to package.json , in your scripts.

How to customize service workers with create-react-app, In the linked post, I discussed how we could go about building a custom Service Worker (SW) while staying within the create-react-app shell. With Create React App Service Worker is only enabled in the production environment, for example when running npm run build. Service Worker is here to help developing a Progressive Web App . A good resource about it in the context of Create React App can be found in their website here .

How to build a PWA with Create-React-App and custom service , Note: This is not a primer on create-react-app or what a service worker is. This post assumes prior knowledge of both. So, I recently had the  In this codelab, you learn how to integrate a service worker into an existing application to make the application work offline. The application is called Air Horner. Click the horn and it makes a sound. What you'll learn. How to add a basic service worker to an existing project.

Comments
  • Comments are not for extended discussion; this conversation has been moved to chat.
  • Dear @Onkar even that, I did not see service-worker working in Google Chrome
  • Has this changed? Because create-react-app doesn't create a registerServiceWorker.js but a serviceWorker.js