【问题标题】:How To Add Service Worker In React Project如何在 React 项目中添加 Service Worker
【发布时间】:2019-05-13 05:15:36
【问题描述】:

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

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

尝试导入错误:“./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 如下:(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();
      });
    }
  }

【问题讨论】:

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


    【解决方案1】:

    从你的错误信息来看,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中,有很多export表达式,但是没有export default。

    【讨论】:

    【解决方案2】:

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

    import * as registerServiceWorker from './registerServiceWorker';

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

    registerServiceWorker.unregister();

    【讨论】:

    • 亲爱的@Onkar,即便如此,我也没有看到服务人员在 Google Chrome 中工作
    【解决方案3】:

    试试这个。

    create-react-app FolderName

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

    【讨论】:

    • 这有改变吗?因为 create-react-app 不会创建一个 registerServiceWorker.js 而是一个 serviceWorker.js
    猜你喜欢
    • 2019-02-16
    • 1970-01-01
    • 2022-10-21
    • 2018-05-18
    • 1970-01-01
    • 2017-06-14
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多