添加 Service Worker 以创建 React App 项目

Add Service Worker to Create React App Project

我正在安装一个名为 Subscribers 的通知系统,其中包含一个使用 create react app 构建的项目。他们要求开发人员下载他们的 service worker 并将其包含在项目的根目录中。我以前从未安装/使用过 Service Worker,这很可能是我误解的根源。

如何将 Service Worker 添加到 React 项目的根目录中?说明说 service worker 应该以 https://yoursite.com/firebase-messaging-sw.js 的形式出现在根目录中。为了注册 URL,我在 src/index.js:

下包含了一个 service worker
import Environment from './Environment'

export default function LocalServiceWorkerRegister() {
    const swPath = `${Environment.getSelfDomain()}/firebase-messaging-sw.js`;
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function() {
        navigator.serviceWorker.register(swPath).then(function(registration) {
          // Registration was successful
          console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
          // registration failed :(
          console.log('ServiceWorker registration failed: ', err);
        });
      });
    }
}

在生产中,我收到 404 错误。我试过将 firebase-messaging-sw.js 文件放在根目录的 src 文件夹下。每次都出现同样的错误。

以下是订阅者的说明: https://subscribers.freshdesk.com/support/solutions/articles/35000013054-diy-installation-instructions

public 文件夹是提供的 'escape hatch' 用于从模块系统外部添加资产。 来自 docs:

If you put a file into the public folder, it will not be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the public folder, you need to use a special variable called PUBLIC_URL

因此,一旦复制到 public 文件夹,您将像这样引用文件:

import Environment from './Environment'

export default function LocalServiceWorkerRegister() {
    const swPath = `${process.env.PUBLIC_URL}/firebase-messaging-sw.js`;
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function() {
        navigator.serviceWorker.register(swPath).then(function(registration) {
          // Registration was successful
          console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }, function(err) {
          // registration failed :(
          console.log('ServiceWorker registration failed: ', err);
        });
      });
    }
}