【问题标题】:How to cache React application in service worker如何在 Service Worker 中缓存 React 应用程序
【发布时间】:2019-06-03 07:18:02
【问题描述】:

我正在尝试从头开始创建 React PWA。到目前为止,我的项目将缩小后的文件输出到 dist/js 文件夹。

在我的 service worker 文件中,我使用 Workbox 来预缓存应用程序。这是我目前的设置:

importScripts("./node_modules/workbox-sw/build/workbox-sw.js");

const staticAssets = [
    "./",
    "./images/favicon.png",
]

workbox.precaching.precacheAndRoute(staticAssets);

目前,如果我从开发工具 > Service Worker 启用 offline,它会引发这些错误并且应用无法加载:

3localhost/:18 GET http://localhost:8080/js/app.min.js net::ERR_INTERNET_DISCONNECTED
localhost/:1 GET http://localhost:8080/manifest.json net::ERR_INTERNET_DISCONNECTED
3:8080/manifest.json:1 GET http://localhost:8080/manifest.json net::ERR_INTERNET_DISCONNECTED
logger.mjs:44 workbox Precaching 0 files. 2 files are already cached.
5:8080/manifest.json:1 GET http://localhost:8080/manifest.json net::ERR_INTERNET_DISCONNECTED

我该如何解决这个问题?

【问题讨论】:

  • 您可以使用PWA in React App 查看此文档。有关于workbox-webpack plugin的详细信息。它将负责生成一个 Service Worker 文件,该文件将自动预缓存您的所有本地资产,并在您部署更新时使它们保持最新。

标签: reactjs progressive-web-apps workbox


【解决方案1】:

这意味着您的资源没有被正确缓存, 您需要在访问之前将它们添加到缓存中, 默认情况下,工作箱会为您完成。 它显示了 2 个缓存的文件,因为它们存在于您的阵列中,预期结果 剩下的也一样。

const staticAssets = [
    "./",
    "./images/favicon.png",
    "./js/app.min.js",
    "./manifest.json",
    { url: '/index.html', revision: '383676' }
]

你可以尝试添加事件监听器,

self.addEventListener('install', event => {
  console.log('Attempting to install service worker and cache static assets');
  event.waitUntil(
    caches.open("staticCacheName")
    .then(cache => {
      return cache.addAll(staticAssets);
    })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(caches.match(event.request)
  .then(function(response) {
      if (response) {
        return response;
      }
      return fetch(event.request);
    })
  );
});

【讨论】:

  • 怎么样?我认为做workbox.precaching.precacheAndRoute(staticAssets); 应该缓存它。
猜你喜欢
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 2017-05-27
相关资源
最近更新 更多