-
Notifications
You must be signed in to change notification settings - Fork 22
/
build-sw.js
92 lines (82 loc) · 2.72 KB
/
build-sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const glob = require('glob');
const fs = require('fs');
const dest = 'dist/sw.js';
const staticAssetsCacheName = 'todo-assets-v6';
const dynamicCacheName = 'todo-dynamic-v6';
let staticAssetsCacheFiles = glob
.sync('dist/**/*')
.map((path) => {
return path.slice(5);
})
.filter((file) => {
if (/\.gz$/.test(file)) return false;
if (/sw\.js$/.test(file)) return false;
if (!/\.+/.test(file)) return false;
return true;
});
staticAssetsCacheFiles = [...staticAssetsCacheFiles];
const stringFileCachesArray = JSON.stringify(staticAssetsCacheFiles);
const serviceWorkerScript = `var staticAssetsCacheName = '${staticAssetsCacheName}';
var dynamicCacheName = '${dynamicCacheName}';
self.addEventListener('install', function (event) {
self.skipWaiting();
event.waitUntil(
caches.open(staticAssetsCacheName).then(function (cache) {
cache.addAll([
'/',
${stringFileCachesArray.slice(1, stringFileCachesArray.length - 1)}
]
);
}).catch((error) => {
console.log('Error caching static assets:', error);
})
);
});
self.addEventListener('activate', function (event) {
if (self.clients && clients.claim) {
clients.claim();
}
event.waitUntil(
caches.keys().then(function (cacheNames) {
return Promise.all(
cacheNames.filter(function (cacheName) {
return (cacheName.startsWith('todo-')) && cacheName !== staticAssetsCacheName;
})
.map(function (cacheName) {
return caches.delete(cacheName);
})
).catch((error) => {
console.log('Some error occurred while removing existing cache:', error);
});
}).catch((error) => {
console.log('Some error occurred while removing existing cache:', error);
}));
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request)
.then((fetchResponse) => {
return cacheDynamicRequestData(dynamicCacheName, event.request.url, fetchResponse.clone());
}).catch((error) => {
console.log(error);
});
}).catch((error) => {
console.log(error);
})
);
});
function cacheDynamicRequestData(dynamicCacheName, url, fetchResponse) {
return caches.open(dynamicCacheName)
.then((cache) => {
cache.put(url, fetchResponse.clone());
return fetchResponse;
}).catch((error) => {
console.log(error);
});
}
`;
fs.writeFile(dest, serviceWorkerScript, function(error) {
if (error) return;
console.log('Service Worker Write success');
});