-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
108 lines (92 loc) · 2.92 KB
/
index.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
'use strict'
const fs = require('fs')
const path = require('path')
const glob = require('glob')
const swPrecache = require('sw-precache')
function getOutputs (output) {
return new Promise((resolve, reject) => {
fs.stat(output, async (error, stats) => {
if (!fs.existsSync(output) || error) {
console.log('[error] Not found')
process.exit(2)
}
const assets = stats.isDirectory()
? await getFiles(output + '/**/*.{css,js}')
: await getFiles(path.dirname(output) + '/**/*.{css,js}')
const base = stats.isDirectory() ? output : path.dirname(output)
const htmls = stats.isDirectory()
? await getFiles(output + '/**/*.html')
: [output]
resolve({ assets, base, htmls })
})
})
}
function getFiles (path) {
return new Promise((resolve, reject) => {
glob(path, (err, data) => resolve(data))
})
}
function hashFile (hash, file) {
return `${path.dirname(file)}/${path.basename(
file,
path.extname(file),
)}-${hash + path.extname(file)}`
}
module.exports = async options => {
const { assets, base, htmls } = await getOutputs(options[0])
const hash = +new Date()
Promise.all([
htmls.map(html =>
fs.readFile(html, 'utf-8', (error, data) => {
if (error) throw error
const htmlBefore = '</body>'
const htmlAfter =
'<script src="service-worker.js"></script><script>if("serviceWorker" in navigator && window.location.protocol === "https:")navigator.serviceWorker.register("/service-worker.js")</script></body>'
fs.writeFile(
html,
data.replace(htmlBefore, htmlAfter),
(error, data) => {
if (error) throw error
console.info(`${html} was saved!`)
},
)
}),
),
assets.map(asset =>
fs.readFile(asset, 'utf-8', (error, data) => {
if (error) throw error
htmls.map(html =>
fs.readFile(html, 'utf-8', (error, data) => {
if (error) throw error
const assetBefore = path.basename(asset)
const assetAfter = `${path.basename(
asset,
path.extname(asset),
)}-${hash + path.extname(asset)}`
fs.writeFile(
html,
data.replace(assetBefore, assetAfter),
(error, data) => {
if (error) throw error
},
)
}),
)
fs.writeFile(hashFile(hash, asset), data, (error, data) => {
if (error) throw error
fs.unlink(asset, (error, data) => {
if (error) throw error
console.info(`${hashFile(hash, asset)} was saved!`)
})
})
}),
),
swPrecache.write(`${base}/service-worker.js`, {
staticFileGlobs: [
base +
'/**/*.{html,js,css,png,jpg,jpeg,gif,svg,ico,eot,ttf,woff,woff2,txt,webapp,json}',
],
stripPrefix: base,
}),
])
}