【发布时间】:2021-06-28 20:10:13
【问题描述】:
我正在尝试使用以下文件系统布局将 serviceworker 添加到现有 React 应用程序: Filesystem
基本一点初始化代码都存放在public文件夹中,所有重要的代码都在src文件夹中。在 serviceWorker.js 文件中,我创建了一个文件名数组来缓存并在“安装”事件侦听器中调用该数组,如果我检查 DevTools,我可以看到文件名存在于缓存中:当我预览数据时然而,Chrome DevTools,我看到缓存文件中的代码都来自 index.html。事实上,我可以将任何我想要的东西添加到文件名数组中,我会在缓存存储中找到它,只是发现它正在存储 index.html 代码。似乎无论我尝试将什么文件添加到缓存中,都只会加载 index.html。
ServiceWorker.js:
let CACHE_NAME = "MG-cache-v2";
const urlsToCache = [
'/',
'/index.html',
'/src/App.js',
'/monkey'
];
self.addEventListener('install', function (event) {
//perform install steps
event.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
console.log('Opened MG_Cache');
return cache.addAll(urlsToCache);
}).catch(function (error) {
console.error("Error loading cache files: ", error);
})
);
self.skipWaiting();
});
self.addEventListener('fetch', function (event) {
event.respondWith(caches.match(event.request).then(function (response) {
if (response) {
return response;
}
return fetch(event.request);
})
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(async function () {
const cacheNames = await caches.keys();
await Promise.all(
cacheNames.filter((cacheName) => {
//Return true if you want to remove this cache,
//but remember that caches are shared across the whole origin
return;
}).map(cacheName => caches.delete(cacheName))
);
})
})
index.html 部分:
<script>
if ('serviceWorker' in navigator)
{
window.addEventListener('load', function () {
navigator.serviceWorker.register('serviceWorker.js').then(function (registration) {
// Registration was successful
console.log("ServiceWorker registration successful with scope: ", registration.scope);
}, function (err) {
// registration failed :
(console.log('ServiceWorker registration failed: ', err));
});
});
}
</script>
Google 开发工具预览: All files are the same
我在文件名数组中尝试了多种命名策略,但都以相同的结果结束。在这一点上,我完全不知所措。
编辑:虽然这并不能解决我的问题,但我发现了另一个问题的 answer,它提供了一些指导。似乎服务器永远找不到我请求的文件,因此返回 index.html。我尝试将 serviceWorker.js 文件放在 src 文件夹中并将 service worker 注册移动到 App.js 并收到错误:
`DOMException: Failed to register a ServiceWorker for scope ('http://localhost:3000/src/') with script ('http://localhost:3000/src/serviceWorker.js'): The script has an unsupported MIME type ('text/html'). `
这表明服务器无法访问 src 文件夹,只能访问公共文件夹。知道为什么会这样吗?
【问题讨论】:
标签: javascript reactjs progressive-web-apps service-worker offline-caching