我正在使用带有 Angular-cli-1.6.0 的 workbox-build-2.1.2 和 workbox-sw-2.1.2,一切正常,但是当我更新应用程序并将其构建用于生产并且 sw.js 文件被修改时然后在 chrome 浏览器中,服务人员没有更新它继续使用旧版本,直到我手动取消注册它。它是否应该不安装新的 sw.js 文件,并且在安装新版本时它还会清理网站旧数据兑现并自动开始新的石板,还是我需要设置该部分?
这是我在 Angulars 主文件中注册 sw.js 的方法:
platformBrowserDynamic()
.bootstrapModule(AppModule)
.then(registerServiceWorker)
.catch(err => console.log(err));
function registerServiceWorker() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('sw.js')
.then(reg => {
log('Registration successful', reg);
reg.onupdatefound = () => {
const installingWorker = reg.installing;
installingWorker.onstatechange = () => {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
log('New or updated content is available', installingWorker);
} else {
log('Content is now available offline', installingWorker);
}
break;
case 'redundant':
console.error('The installing service worker became redundant', installingWorker);
break;
default:
log(installingWorker.state);
break;
}
};
};
})
.catch(e => {
console.error('Error during service worker registration:', e);
});
} else {
console.warn('Service Worker is not supported');
}
}
我用 npm 运行的 generate-sw 文件
const workboxBuild = require('workbox-build');
const SRC_DIR = 'src';
const BUILD_DIR = 'public';
const SW = 'sw.js';
const globPatterns = [
"**/*.{ico,html,css,js,woff,json}"
];
const globIgnores = [
"sw.js"
];
const input = {
swSrc: `${SRC_DIR}/${SW}`,
swDest: `${BUILD_DIR}/${SW}`,
globDirectory: BUILD_DIR,
globPatterns: globPatterns,
globIgnores: globIgnores,
maximumFileSizeToCacheInBytes: 4000000
};
workboxBuild.injectManifest(input).then(() => {
console.log(`The service worker ${BUILD_DIR}/${SW} has been injected`);
});
和基础 sw.js 文件
importScripts('workbox-sw.prod.v2.1.2.js');
const workboxSW = new self.WorkboxSW({clientsClaim: true});
workboxSW.precache([]);
workboxSW.router.registerNavigationRoute('/index.html');
*****更新*****
将 express.js 用于开发服务器,我将 Cache-Control 设置为零,现在当我重新加载页面时,服务工作者会更新到较新的版本。我在生产中感到困惑,将 Cache-Control 设置为天/年,服务工作者需要多长时间才能更新,它会清除旧的现金和 indexDB,还是我们必须手动完成
这是快递的代码:
app.use('/', express.static(publicFolderPath, {maxAge: 0}));
app.get('*', (req, res) => {
res.sendFile('index.html');
});