首页 > 解决方案 > Serviceworker - WorkBox v3.5 在 CRA 中“找不到注入清单的地方”

问题描述

我正在尝试用自定义替换默认的 React 应用程序服务人员,因为它将索引路由设置为“index.html”,而我需要将它转到“200.html”以进行 react-snap。

我完全按照本指南https://github.com/facebook/create-react-app/issues/5673#issuecomment-438654051

但得到错误:

UnhandledPromiseRejectionWarning: Error: Unable to find a place to inject the manifest. Please ensure that your service worker file contains the following: self.__WB_MANIFEST
    at Object.injectManifest

我的 sw.js 看起来像这样 -

if ("function" === typeof importScripts) {
  importScripts(
    "https://storage.googleapis.com/workbox-cdn/releases/3.5.0/workbox-sw.js"
  );
  /* global workbox */
  if (workbox) {
    console.log("Workbox is loaded");

    /* injection point for manifest files.  */
    workbox.precaching.precacheAndRoute([]);

    /* custom cache rules*/
    workbox.routing.registerNavigationRoute("/200.html", {
      blacklist: [/^\/_/, /\/[^\/]+\.[^\/]+$/],
    });

    workbox.routing.registerRoute(
      /\.(?:png|gif|jpg|jpeg)$/,
      workbox.strategies.cacheFirst({
        cacheName: "images",
        plugins: [
          new workbox.expiration.Plugin({
            maxEntries: 60,
            maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
          }),
        ],
      })
    );
  } else {
    console.log("Workbox could not be loaded. No Offline support");
  }
}

我在其他 stackoverflow 上搜索并查看的所有内容都表明您需要包含

  workbox.precaching.precacheAndRoute([]);

我是谁。所以我不知道为什么它不起作用?

我运行工作箱的反应脚本:

 "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts --max_old_space_size=4096 build && npm run build-sw",
    "build-sw": "node ./src/sw-build.js",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "postbuild": "react-snap"
  },

标签: reactjsservice-workerworkboxreact-snap

解决方案


问题是 workbox-build 的版本是 5.0,而代码/脚本使用的是 3.5.0。

在我的 package.json 中降级到 3.5.0 解决了这个问题。


推荐阅读