如何在服务工作者中缓存动态 url?它与预缓存有什么关系吗?我正在使用 ReactJS 默认的 serviceWorker

How can I cache dynamic urls in service worker? Does it has anything to do with precache? I am using ReactJS default serviceWorker

在我的 Main.js 文件中,我有以下代码:

import * as serviceWorker from './serviceWorker';
/*
some code
*/
ReactDOM.render(<Main />,document.getElementById('app'));
serviceWorker.register()

这个 serviceWorker 默认是从 create-react-app 操作创建的,但我不得不从源代码复制它,因为我没有使用 create-react-app 创建应用程序。

serviceWorker 在 / 范围内查找 'service-worker.js' 文件。在以下行中:

const swUrl = `/service-worker.js`;

使用此配置,我能够缓存服务-worker.js 文件的 PrecacheConfig 变量中提到的所有内容,例如 /js/app.js

当涉及动态 url 时,例如 /myapp/{id}/test/。我确定不应该对所有这些动态 url 进行预缓存,当用户访问页面时应该缓存它们,但是我应该在哪里以及如何缓存它们?

我建议使用 Workbox https://developers.google.com/web/tools/workbox to manage your Service Worker functionality. Using workbox.routing module (https://developers.google.com/web/tools/workbox/modules/workbox-routing) 您可以使用特定于您的应用程序的正则表达式来指定用于兑现的自定义规则。

希望对您有所帮助!