我将 Vue.js 用于我的一个站点,当我构建站点时,服务工作者的预缓存清单与文件夹importScripts
中的两个不同。dist
例如,precache-manifest.0933a0358a370c8b40e7cbc458f7c9e0.js
并且precache-manifest.0e6f804c2e2176694870b3eab65d85b9.js
在dist
文件夹中,但服务人员指定precache-manifest.d9356e6d41d3366f8829dce3dcc327a0.js
. 我使用 Vue.js CLI 服务作为基础,并且我将 PWA 插件配置为InjectManifest
使用我的服务工作者。
然后,此文件名差异会导致以下两个错误:Failed to register/update a ServiceWorker for scope ‘https://example.com’: Bad Content-Type of ‘text/html’ received for script ‘/precache-manifest.d9356e6d41d3366f8829dce3dcc327a0.js’. Must be a JavaScript MIME type.
和Error during service worker registration: TypeError: ServiceWorker script at https://example.com/service-worker.js for scope https://example.com threw an exception during script evaluation.
我的文件的相关部分vue.config.js
如下:
pwa: {
workboxPluginMode: "InjectManifest",
workboxOptions: {
swSrc: "src/service-worker.js",
exclude: [/\.map$/, /social_preview\.png/],
},
}
我的服务人员(在 Workbox 注入之前importScripts
):
/* eslint-disable no-undef, no-restricted-globals */
// Source: https://dev.to/drbragg/handling-service-worker-updates-in-your-vue-pwa-1pip
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
// The precaching code provided by Workbox
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
// Source: https://dev.to/voodu/vue-3-pwa-service-worker-12di
const cacheExpirationTime = new Date(new Date().getTime() + 86400000);
const cacheRemainingTime = Math.floor(
(cacheExpirationTime.getTime() - new Date().getTime()) / 1000
);
workbox.routing.registerRoute(
/\.(?:png|ico|gif|jpg|jpeg|svg)$/,
new workbox.strategies.StaleWhileRevalidate({
cacheName: "images",
plugins: [
new workbox.expiration.Plugin({
maxEntries: 60,
maxAgeSeconds: cacheRemainingTime,
}),
],
})
);
我还使用了现代构建命令 ( vue-cli-service build --modern
),它创建了两个版本的 JS 文件,遗留文件和模块文件。
提前致谢!