我正在尝试 super 优化 PWA通过尽可能地组合和缩小。我的应用程序主要基于 google tutorial在服务工作人员上 - 因此我在我的服务工作人员中有这样的代码:
var filesToCache = [
'/',
'/index.html',
'/scripts/app.js',
'/styles/inline.css'
];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(filesToCache);
})
);
});
我有一个 gulpfile.js
,其中使用 gulp-smoosher
在构建期间内联我的 css:
<!-- smoosh -->
<link rel="stylesheet" type="text/css" href="styles/inline.css">
<!-- endsmoosh -->
效果很好 - 它将我的 css 直接内联到 HTML 中 - 但显然我的 serviceworker 中的 filesToCache
现在有一个在构建中不存在的条目
var filesToCache = [
'/',
'/index.html',
'/scripts/app.js',
'/styles/inline.css' // <!--- this shouldn't be here in the build
];
是否有任何选项,使用 gulp 任务或其他方式(也许可以在构建时更新某种配置)来解决此问题?
最佳答案
我最终通过进行以下更改解决了这个问题。
- 将
filesToCache
变量移至其自己的 json 文件 -filesToCache.json
- 更新我的 Service Worker 以在
安装
期间加载该文件 - 使用
gulp-json-editor
在构建时操作文件。
gulpfile 中的代码
const jsonEditor = require('gulp-json-editor');
// snip
gulp.task("filesToCache", function(){
var out = folder.build;
return gulp.src(folder.src + "filesToCache.json")
.pipe(jsonEditor(function(json){
json.splice(json.indexOf("/styles/inline.css"),1);
return json;
}))
.pipe(gulp.dest(out));
});
服务 worker 中的代码
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
return fetch("/filesToCache.json").then(function(response){
if(response && response.ok){
return response.json()
}
throw new Error("Failed to load files to cache for app shell")
})
.then(function(filesToCache){
console.log('[ServiceWorker] Caching app shell', filesToCache);
return cache.addAll(filesToCache);
})
.catch(function(error){
console.error(error)
})
})
);
});
希望这对将来的人有帮助!
关于javascript - 使用 gulp 更新 serviceworker 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45978907/