React PWA 无法安装

React PWA not installable

我正在用 React 开发一个应用,我想把它变成一个 PWA,所以我按照 this tutorial 添加了我自己的缓存规则。 Service Worker 工作,模板如下所示:

function run() {
  if ('function' === typeof importScripts) {
    importScripts(
      'https://storage.googleapis.com/workbox-cdn/releases/3.5.0/workbox-sw.js'
    );

    /* Global workbox */
    if(!workbox) return;
    workbox.setConfig({ debug: false });

    /* Injection point for manifest files. */
    workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);

    /* Custom cache rules */
    workbox.routing.registerRoute(
      ({ url }) => url.origin === "https://www.instagram.com",
      workbox.strategies.cacheFirst({
        cacheName: 'instagram',
        plugins: [
          new workbox.expiration.Plugin({ maxAgeSeconds: 24 * 60 * 60 }),
        ],
      })
    );
  }
}

run();

SW 工作正常,它缓存了它应该缓存的内容。清单正在通过,start_url 字段与我在其中托管 React App 的子文件夹相同,但我仍然收到错误

No matching service worker detected. You may need to reload the page, or check that the scope of the service worker for the current page encloses the scope and start URL from the manifest. My manifest looks like this:

{
  "short_name": "ReactApp",
  "name": "My React App",
  "description": "blah blah blah",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": "/reactapp",
  "display": "standalone",
  "theme_color": "#7b1fa2",
  "background_color": "#7b1fa2"
}

正如我所说,服务工作者完美地完成了它的工作,但浏览器似乎并不认为它是可安装的。可能是什么?

原来我的 manifest.json 少了一个字符。在 运行 灯塔审计之后,我发现 service worker 的范围是 https://example.net/reactapp/start_urlhttps://example.net/reactapp 最后没有斜线。所以我所做的就是改变这个:

{
  ...
  "start_url": "/reactapp",
  ...
}

...为此:

{
  ...
  "start_url": "/reactapp/",
  ...
}