-
Notifications
You must be signed in to change notification settings - Fork 1
/
sw-generator.js
52 lines (41 loc) · 1.54 KB
/
sw-generator.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
/* global require process console */
const { lstatSync, readdirSync, readFileSync, writeFileSync } = require('fs');
const { join } = require('path');
const { log } = console;
const config = require('./web/config');
// Function to get a recursive list of files in a folder
const inflateInput = (inputDirs, parentDir = './') =>
inputDirs.map(
inputDir =>
(
item =>
lstatSync(item).isDirectory()
? inflateInput(readdirSync(item), item)
: [item]
)(join(parentDir, inputDir))
).reduce(
(a, c) => a.concat(c),
[]
);
log('Generating service-worker file...');
// Generate list of files in 'public' directory
const listOfFiles = inflateInput(['public']);
// Read sw.js template as string
const swTemplateString = readFileSync('./assets/sw-template.js', 'utf8');
// Get stringified list of files with static path
const stringifiedOutputFileList = JSON.stringify(
['/']
.concat(
listOfFiles
.map(
filename => filename.replace('public', `/${config.staticPath}`)
)
)
);
// Generate output file contents post substitution
const compiledContentOfOutputFile = swTemplateString
.replace(/'swCacheString'/g, new Date().getTime())
.replace(/'outputFileList'/g, stringifiedOutputFileList);
// Write final sw.js to public directory
writeFileSync('./public/sw.js', compiledContentOfOutputFile);
log('Service-worker file generated!');