如何在 React 项目中添加 Service Worker

IT技术 reactjs service-worker progressive-web-apps
2021-05-10 04:02:07

我想在我的react项目中添加服务工作者。项目已准备就绪,但默认服务似乎不起作用。

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

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

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

如果我像无react(框架)应用程序一样添加我自己的自定义 serviceWorker 文件,它是否适用于react案例?

目前我的 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 如下:(React 的默认代码)

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个回答

从你的错误信息来看,registerServiceWorker.js 文件有问题。

import registerServiceWorker from './registerServiceWorker';

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

export registerServiceWorker

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

export default registerServiceWorker

编辑:

用这个来导入js文件

import * as registerServiceWorker from './registerServiceWorker';

并像这样使用它:

registerServiceWorker.unregister();

编辑2:

我想你对导入/导出有一些误解,所以我在这里解释一下。

如果我们想将某个文件(例如 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. 您可能会看到另一种导入方式。像这样:

    import * as registerServiceWorker from './registerServiceWorker';

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

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

您可以使用以下命令导入从 registerServiceWorker.js 文件中导出的所有函数

import * as registerServiceWorker from './registerServiceWorker';

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

registerServiceWorker.unregister();

试试这个。

create-react-app FolderName

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