我正在从空白 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 代码,这并不理想。
所以我的问题是:
- 有没有办法
maximumFileSizeToCacheInBytes
在 CRA 应用程序中强制限制为自定义值? - 我正在考虑在构建过程之后尝试获取哈希码并自动更新 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;
});
});
})
);
});
我希望我说清楚了。
在此先感谢弗朗切斯科