Fra*_*tti 7 reactjs service-worker progressive-web-apps create-react-app cra
我正在从空白的 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 中进行配置:(
由于音频质量要求,我无法减小文件大小。
我还编写了一个自定义软件逻辑来预先缓存来自互联网的外部资源,并且我考虑在那里添加音频文件。但是 React 构建过程会根据文件内容向文件名添加哈希码,因此每次更新音频内容时我都需要更改 SW 代码,这并不理想。
所以我的问题是:
maximumFileSizeToCacheInBytes在 CRA 应用程序中强制限制自定义值?这是我的 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;
});
});
})
);
});
Run Code Online (Sandbox Code Playgroud)
我希望我说清楚了。
预先感谢,弗朗西斯科
经过一番研究,我找到了两个解决方案:
\n第一个解决方案通常不被鼓励,因为之后您需要自己管理所有配置。\n这里有一些关于它的阅读:
\n\n因此,按照这些文章中的建议,我查看了可用的工具。我发现:
\n\n长话短说,我无法让它与前两个一起工作,但我做到了craco。\n我必须定制一个插件来实现我所需要的,但我终于做到了。
特别是我分叉了这个包 - craco-workbox- 添加了覆盖配置的可能性InjectManifest,其中是maximumFileSizeToCacheInBytes。
通过这种方式,我将限制提高到 25MB,效果非常好;)
\n如果有人需要这个:
\n更新\n我的 PR 已合并,因此现在该功能可用并在craco-workboxv0.2.0 版本下的插件中发布
| 归档时间: |
|
| 查看次数: |
3802 次 |
| 最近记录: |