如何在 React 项目中添加 Service Worker [英] How To Add Service Worker In React Project

查看:182
本文介绍了如何在 React 项目中添加 Service Worker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 React 项目中添加 Service Worker.项目已准备就绪,默认服务似乎不起作用.

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:

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

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

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

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

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

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

目前我的 index.js 中有这些代码

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

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

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

我使用的 Service Worker 如下:(React 的默认代码)

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

推荐答案

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

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

import registerServiceWorker from './registerServiceWorker';

然而,在 registerServiceWorker.js 文件中没有以下内容

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

export registerServiceWorker

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

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

export default registerServiceWorker

<小时>

用它来导入js文件


Use this to import js files

import * as registerServiceWorker from './registerServiceWorker';

像这样使用它:

registerServiceWorker.unregister();

<小时>

编辑 2:

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


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

如果我们想将某个文件(例如 child.js)导入另一个文件(例如 parent.js)中.在 child.js 这样的文件中,它必须有导出.

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.

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

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

const child = () => {

}
export default Child

我们将可以像下面这样在parent.js中导入它.使用默认表达式,我们实际上可以在下面的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. 您可能会看到另一种导入方式.就像这样:

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

import * as registerServiceWorker from './registerServiceWorker';

import * as registerServiceWorker from './registerServiceWorker';

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

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

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

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

这篇关于如何在 React 项目中添加 Service Worker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆