How To Add Service Worker In React Project

2019-08-17 08:55发布

问题:

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();
      });
    }
  }

回答1:

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();



回答2:

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.



回答3:

Try this.

create-react-app FolderName

Is just auomatically creates a registerServiceWorker for your app