-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate-sw.js
87 lines (75 loc) · 2.16 KB
/
generate-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
const fs = require('fs');
const path = require('path');
const globby = require('globby');
const loadJsonFile = require('load-json-file');
const dotNext = path.resolve(__dirname, './.next');
const target = path.resolve(__dirname, './.next/service-worker.js');
function bundles(app) {
return new Promise((resolve, reject) => {
fs.readdir(`${dotNext}/bundles/pages`, (err, files) => {
if (err) {
resolve(app);
}
if (files) {
const root = `/_next/${app.buildId}/page`;
app.precaches = app.precaches.concat(
files.filter(file => file !== 'index.js').map(file => {
// req /_next/22321e97-8895-48db-b915-82e255f3faa8/new
return path.join(root, file.replace(/.js$/, ''));
})
);
}
resolve(app);
});
});
}
function chunks(app) {
return new Promise((resolve, reject) => {
fs.readdir(`${dotNext}/chunks`, (err, files) => {
if (err) {
resolve(app);
}
if (files) {
const root = `/_next/webpack/chunks`;
app.precaches = app.precaches.concat(
files.filter(file => /\.js$/.test(file)).map(file => {
// req /_next/webpack/chunks/22321e97-8895-48db-b915-82e255f3faa8.js
return path.join(root, file);
})
);
}
resolve(app);
});
});
}
function app() {
const app = {
buildId: fs.readFileSync(`${dotNext}/BUILD_ID`, 'utf8'),
precaches: [],
};
return loadJsonFile(`${dotNext}/build-stats.json`).then(stats => {
Object.keys(stats).map(src => {
// /_next/9265fa769281943ee96625770433e573/app.js
app.precaches.push(`/_next/${stats[src].hash}/${src}`);
});
return app;
});
}
const swSnippet = precache =>
`importScripts('https://unpkg.com/[email protected]')
const workboxSW = new WorkboxSW({clientsClaim: true})
// set precahe listed item
workboxSW.precache(${precache})
// cache very first page by sw
workboxSW.router.registerRoute(
'/',
workboxSW.strategies.staleWhileRevalidate()
)
`;
app().then(chunks).then(bundles).then(app => {
fs.writeFileSync(
target,
swSnippet(JSON.stringify(app.precaches, null, 2)),
'utf8'
);
});