如何通过 Next.js PWA 中的 Service Worker 访问 src 文件夹库

发布于 2025-01-13 10:14:43 字数 1123 浏览 3 评论 0原文

我面临着一个设计挑战,涉及如何由 Next.js 渐进式 Web 应用程序 (PWA) 中的 Service Worker 重用库。

我的 PWA 的文件夹结构如下所示:
输入图片此处描述

关于结构:

  • /public 文件夹中,有一个名为 sw.js 的 Service Worker
  • /src/lib > 文件夹包含一个用于 IndexedDB 操作的 IDBManager.js
  • /src/api 文件夹包含一个 IDB.js 作为执行 IndexedDB 操作的 API 端点。 IDB.js 导入 IDBManager.js

情况是 sw.js 服务工作人员只能访问其范围内的文件,即同一目录和子文件夹中的文件。为了由服务工作线程执行 IndexedDB 操作,我必须将 IDBManager.js 的代码复制到公共文件夹中的文件中。

为了防止重复代码,我的想法是为服务工作人员提供 API 端点 (IDB.js),服务工作人员可以通过 fetch() 访问该端点调用。

Service Worker 的 fetch() 调用有效,但在调用 openDB() 打开 IndexedDB 时,IDB.js 出现错误。错误信息是:
输入图片此处描述

当 Service Worker 未调用 openDB() 时,不会出现此错误。有谁知道这个错误的原因是什么,或者如何设计一个由服务工作者重用代码的 PWA?

I'm facing a design challenge regarding how to reuse libraries by a service worker in a Next.js progressive web app (PWA)

The folder structure of my PWA looks like this:
enter image description here

About the structure:

  • Within the /public folder there's a service worker called sw.js
  • The /src/lib folder contains a IDBManager.js for IndexedDB opertions
  • The /src/api folder contains a IDB.js as an API endpoint to execute IndexedDB operations. The IDB.js imports the IDBManager.js.

The situation is that the sw.js service worker can just access files in its scope that means in the same directory and subfolders. In order to execute IndexedDB opertions by the service worker I would have to duplicate code of IDBManager.js to a file in the public folder.

To prevent duplicate code my idea is to provide the service worker the API endpoint (IDB.js) which can be reached by the service worker via a fetch() call.

The service worker's fetch() call works but IDB.js gives an error when calling openDB() to open the IndexedDB. The error message is:
enter image description here

This error doesn't appear when openDB() is not called by the service worker. Does anyone have an idea what the reason for this error is or how to design a PWA with code reuse by the service worker?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文