2017-08-31 22 views
2

我試圖通過儘可能多地組合和縮小來超級優化PWA。我的應用程序主要是基於一個google tutorial的服務人員 - 正因爲如此我有代碼,如這在我的服務人員:使用gulp更新服務人員配置

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 - 但顯然我filesToCache在我serviceworker現在有了在構建不會存在的條目

var filesToCache = [ 
    '/', 
    '/index.html', 
    '/scripts/app.js', 
    '/styles/inline.css' // <!--- this shouldn't be here in the build 
]; 

是否有任何選項,使用一個吞嚥任務或其他方式(也許某種配置這可以在生成更新)來解決這個問題?

回答

2

我最終通過做出以下更改來解決此問題。

  • 移動filesToCache變量自身的JSON文件 - filesToCache.json
  • 更新我的服務人員來加載在該文件中install
  • 使用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)); 
}); 

代碼在服務人員

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) 
     }) 
    }) 
); 
}); 

希望這可以幫助別人的未來!