如何在React项目中添加Service Worker

时间:2018-12-12 06:29:38

标签: reactjs service-worker progressive-web-apps

我想在我的React项目中添加服务人员。 项目已准备就绪,默认服务似乎无法正常工作。

即使我尝试导入它,也会出现此错误:

尝试导入错误:“ ./ registerServiceWorker”不包含默认导出(导入为“ registerServiceWorker”)。

此外,如何在默认版本的serviceWorker文件中添加要缓存的文件。

如果我像无反应(框架)应用程序一样添加自己的自定义serviceWorker文件,它将适用于反应情况吗?

目前,我的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();

并在其中说:“尝试导入错误:'./registerServiceWorker'不包含默认导出(导入为'registerServiceWorker')。“

我正在使用的Service Worker如下:(反应的默认代码)

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

3 个答案:

答案 0 :(得分:0)

从您的错误信息中,registerServiceWorker.js文件有问题。

import registerServiceWorker from './registerServiceWorker';

但是,在registerServiceWorker.js文件中没有以下

export registerServiceWorker

因此,我建议将以下内容添加到registerServiceWorker.js

export default registerServiceWorker

编辑:

使用它导入js文件

import * as registerServiceWorker from './registerServiceWorker';

并像这样使用它:

registerServiceWorker.unregister();

Edit2:

我认为您对导入/导出有一些误解,所以我将在这里进行解释。

如果我们想将某个文件(例如child.js)导入另一个文件(例如parent.js)。在child.js之类的文件中,它必须具有导出功能。

有一些方法可以做到这一点。 1.在Child.js中

const child = () => {

}
export default Child

我们将能够将其导入如下所示的parent.js中。使用默认表达式,我们实际上可以在下面的Child位置使用任何名称(通常保持不变)

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

  1. 您可能会看到另一种导入方式。像这样:

    从'./registerServiceWorker'中导入*作为registerServiceWorker;

*表示registerServiceWorker.js中的所有内容。“ as registerServiceWorker”为所有内容命名,以便我们轻松导入。

导入文件的方式,因为在registerServiceWorker.js中,有很多导出表达式,但没有导出默认值。

答案 1 :(得分:0)

您可以使用

导入从registerServiceWorker.js文件导出的所有功能。
  

从'./registerServiceWorker'中导入*作为registerServiceWorker;

之后,您可以调用该文件到index.js文件的任何方法,例如-

  

registerServiceWorker.unregister();

答案 2 :(得分:0)

尝试一下。

create-react-app FolderName

只是为您的应用自动创建了一个registerServiceWorker

相关问题