首页 > 解决方案 > Create React App PWA service worker 中缓存大小限制的解决方法

问题描述

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

不幸的是,我有 5 到 10 MB(音频文件)之间的多个内容,并且在 Create React App Service Worker 中,限制设置为 5MB(以前是 2MB - 请参见此处)。

这些文件没有预先缓存,而且我在构建过程中确实收到了警告: /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 代码,这并不理想。

所以我的问题是:

这是我的 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;
              });
          });
      })
  );
});

我希望我说清楚了。

在此先感谢弗朗切斯科

标签: reactjscreate-react-appprogressive-web-appsservice-workercra

解决方案


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

  • 退出 CRA
  • 使用工具覆盖配置

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

因此,正如那些文章中所建议的,我查看了可用的工具。我发现:

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

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

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

如果有人需要这个:

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


推荐阅读