【问题标题】:Workaround for cache size limit in Create React App PWA service workerCreate React App PWA service worker 中缓存大小限制的解决方法
【发布时间】:2021-11-07 03:08:09
【问题描述】:

我正在从空白 CRA 模板开始开发 PWA。安装后应用程序需要完全离线工作,所以我正在利用 Workbox 的方法来预缓存所有静态内容。

不幸的是,我有几个 5 到 10 MB 的内容(音频文件),在 Create React App Service Worker 中,限制设置为 5MB(以前是 2MB - 请参阅 here)。

这些文件没有被预缓存,而且我确实在构建过程中收到了警告: /static/media/song.10e30995.mp3 is 5.7 MB, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit..

遗憾的是,maximumFileSizeToCacheInBytes 似乎无法在 CRA SW 中配置:(

由于音频质量要求,我无法减小文件大小。

我还编写了一个自定义 SW 逻辑来预缓存来自 Internet 的外部资源,我想在那里添加音频文件。但是 React 构建过程会根据文件名的内容向文件名添加一个哈希码,因此我每次更新音频内容时都需要更改 SW 代码,这并不理想。

所以我的问题是:

  • 有没有办法在 CRA 应用程序中强制 maximumFileSizeToCacheInBytes 限制为自定义值?
  • 我想尝试在构建过程之后获取哈希码并自动更新 SW 代码,但对我来说不是很有说服力。
  • 还有其他解决方案或方法可以实现我的需要吗?

这是我的 SW 代码(默认 CRA 代码 + 最后是我的自定义逻辑)

import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';

import packageJson from '../package.json';


clientsClaim();

// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);

// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
  // Return false to exempt requests from being fulfilled by index.html.
  ({ request, url }) => {
    // If this isn't a navigation, skip.
    if (request.mode !== 'navigate') {
      return false;
    } // If this is a URL that starts with /_, skip.

    if (url.pathname.startsWith('/_')) {
      return false;
    } // If this looks like a URL for a resource, because it contains // a file extension, skip.

    if (url.pathname.match(fileExtensionRegexp)) {
      return false;
    } // Return true to signal that we want to use the handler.

    return true;
  },
  createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);

// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
  // Add in any other file extensions or routing criteria as needed.
  ({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'), // Customize this strategy as needed, e.g., by changing to CacheFirst.
  new StaleWhileRevalidate({
    cacheName: 'images',
    plugins: [
      // Ensure that once this runtime cache reaches a maximum size the
      // least-recently used images are removed.
      new ExpirationPlugin({ maxEntries: 50 }),
    ],
  })
);

// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

// Any other custom service worker logic can go here.
const CUSTOM_PRECACHE_NAME = `custom-precache-v${packageJson.version}`;

const CUSTOM_PRECACHE_URLS = [
 // ... external resources URLs here
];

self.addEventListener('install', event => {
  const now = new Date();
  console.log(`PWA Service Worker adding ${CUSTOM_PRECACHE_NAME} - :: ${now} ::`);
  event.waitUntil(caches.open(CUSTOM_PRECACHE_NAME)
    .then(cache => {
      return cache.addAll(CUSTOM_PRECACHE_URLS)
        .then(() => {
          self.skipWaiting();
        });
    }));
});

// The fetch handler serves responses for same-origin resources from a cache.
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(resp => {

        // @link https://stackoverflow.com/questions/48463483/what-causes-a-failed-to-execute-fetch-on-serviceworkerglobalscope-only-if
        if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
          return;
        }

        return resp || fetch(event.request)
          .then(response => {
            return caches.open(CUSTOM_PRECACHE_NAME)
              .then(cache => {
                cache.put(event.request, response.clone());
                return response;
              });
          });
      })
  );
});

我希望我说清楚了。

提前致谢, 弗朗切斯科

【问题讨论】:

    标签: reactjs create-react-app progressive-web-apps service-worker cra


    【解决方案1】:

    经过一番研究,我找到了两个解决方案:

    • 从 CRA 中弹出
    • 使用工具覆盖配置

    第一个解决方案通常不受欢迎,因为之后您需要自己管理所有配置。 这里有一些关于它的读物:

    因此,按照这些文章中的建议,我查看了可用的工具。我发现:

    长话短说,前两个我不能让它工作,但我用craco做到了。 我不得不定制一个插件来实现我所需要的,但我终于做到了。

    特别是我分叉了这个包 - craco-workbox - 添加了覆盖 InjectManifest 配置的可能性,maximumFileSizeToCacheInBytes 所在的位置。

    这样我将限制提高到 25MB,它就像一个魅力;)

    如果有人需要这个:

    更新 我的 PR 已合并,所以现在该功能可用并在 v0.2.0 版下的 craco-workbox 插件中发布

    【讨论】:

    • 谢谢!您的示例和 craco-workbox 代码对我有用 :)
    猜你喜欢
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    • 2016-12-12
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    相关资源
    最近更新 更多