[英]Workaround for cache size limit in Create React App PWA service worker
I'm developing a PWA starting from a blank CRA template.我正在从空白 CRA 模板开始开发 PWA。 The application needs to fully work offline after the installation, so I'm exploiting Workbox's methods to precache all static content.
安装后应用程序需要完全脱机工作,所以我正在利用 Workbox 的方法来预缓存所有静态内容。
Unfortunately I have severals contents between 5 and 10 MB (audio files) and in the Create React App Service Worker the limit is set to 5MB (previosly 2MB - see here ).不幸的是,我有 5 到 10 MB(音频文件)之间的多个内容,并且在 Create React App Service Worker 中,限制设置为 5MB(以前是 2MB - 请参见此处)。
Those files are not precached and indeed i get warnings during the build process: /static/media/song.10e30995.mp3 is 5.7 MB, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit.
这些文件没有被预缓存,实际上我在构建过程中收到警告:
/static/media/song.10e30995.mp3 is 5.7 MB, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit.
/static/media/song.10e30995.mp3 is 5.7 MB, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit.
. .
Pity that maximumFileSizeToCacheInBytes
seems not to be configurable in CRA SW :(遗憾的是
maximumFileSizeToCacheInBytes
似乎无法在 CRA SW 中配置:(
I cannot decrese the files size because of audio quality requirements.由于音频质量要求,我无法减小文件大小。
I also wrote a custom SW logic to precache external resources from the internet and I thought of adding the audio files there.我还编写了一个自定义 SW 逻辑来预缓存来自 Internet 的外部资源,我想在那里添加音频文件。 but the React build process adds an hashcode to the filenames based on their content, so I would need to change the SW code every time I update the audio content, and that's not ideal.
但是 React 构建过程会根据文件名的内容向文件名添加一个哈希码,因此我每次更新音频内容时都需要更改 SW 代码,这并不理想。
So my questions are:所以我的问题是:
maximumFileSizeToCacheInBytes
limit to a custom value, within a CRA application?maximumFileSizeToCacheInBytes
限制为自定义值? Here's my SW code (the default CRA code + my custom logic at the end)这是我的 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;
});
});
})
);
});
I hope I made myself clear.我希望我说清楚了。
Thanks in advance, Francesco在此先感谢弗朗切斯科
After some research I found two solutions:经过一番研究,我找到了两个解决方案:
The first solution is often discouraged because after that you'd need to manage all the configurations yourself.第一个解决方案通常不受欢迎,因为之后您需要自己管理所有配置。 Here's some reads about it:
这里有一些关于它的读物:
So, as suggested in those articles, I took a look to the available tools.因此,正如那些文章中所建议的,我查看了可用的工具。 I found:
我发现:
Long story short, I could NOT make it work with the first two, but I did with craco
.长话短说,我不能让它与前两个一起工作,但我用
craco
做到了。 I had to customize a plugin to achieve what I needed, but I finally made it.我不得不定制一个插件来实现我所需要的,但我终于做到了。
In particular I forked this package - craco-workbox
- adding the possibility to override also the InjectManifest
config, where the maximumFileSizeToCacheInBytes
is.特别是我分叉了这个包 -
craco-workbox
- 添加了覆盖InjectManifest
配置的可能性,其中maximumFileSizeToCacheInBytes
是。
This way i raised the limit to 25MB and it works like a charm ;)这样我将限制提高到 25MB,它就像一个魅力;)
If anyone needs this:如果有人需要这个:
UPDATE My PR has been merged so now the feature is available and released in craco-workbox
plugin under version v0.2.0更新我的 PR 已合并,因此现在该功能可用并在
craco-workbox
插件中发布,版本为 v0.2.0
It should work with react-app-rewired to override the webpack configs, especially if you upgrade to latest react-scripts that uses webpack 5 you will need others as well.它应该与 react-app-rewired 一起使用以覆盖 webpack 配置,特别是如果您升级到使用 webpack 5 的最新 react-scripts,您也将需要其他配置。 Here's my config override
这是我的配置覆盖
const webpack = require('webpack');
const WorkBoxPlugin = require('workbox-webpack-plugin');
module.exports = {
webpack: (config, env) => {
const fallback = config.resolve.fallback || {};
Object.assign(fallback, {
assert: require.resolve('assert/'),
buffer: require.resolve('buffer'),
path: require.resolve('path-browserify'),
process: require.resolve("process/browser"),
stream: require.resolve('stream-browserify'),
crypto: require.resolve('crypto-browserify'),
http: require.resolve('stream-http'),
https: require.resolve('https-browserify'),
fs: false,
tls: false,
net: false,
os: require.resolve('os-browserify/browser'),
util: require.resolve('util/'),
zlib: require.resolve('browserify-zlib'),
});
config.resolve.fallback = fallback;
config.plugins.forEach(plugin => {
if ( plugin instanceof WorkBoxPlugin.InjectManifest) {
plugin.config.maximumFileSizeToCacheInBytes = 50*1024*1024;
}
});
config.plugins = [
...config.plugins,
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
process: 'process/browser',
}),
];
config.module.rules.push(
{
test: /\.(js|mjs|jsx)$/,
enforce: 'pre',
loader: require.resolve('source-map-loader'),
resolve: {
fullySpecified: false,
},
}
);
config.ignoreWarnings = [/Failed to parse source map/]; // gets rid of a billion source map warnings
return config;
},
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.