-
-
Notifications
You must be signed in to change notification settings - Fork 74
/
build.js
executable file
·79 lines (71 loc) · 1.99 KB
/
build.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
/* eslint-disable no-console */
'use strict'
const fs = require('fs')
const path = require('path')
const bresolve = require('browser-resolve')
const src = path.join(__dirname, 'src')
const dist = path.join(__dirname, 'dist')
try {
fs.rmSync(dist, {
recursive: true,
force: true,
})
} catch (ignored) {
console.warn(`Warning: could not delete "${dist}"`)
}
const have = new Set()
const needed = new Set()
const transform = new Set()
try {
fs.mkdirSync(dist)
} catch (ignored) {
console.warn(`Warning: could not create "${dist}"`)
}
// eslint-disable-next-line prefer-named-capture-group
const script = /<script\s+src="([^'"/]+)"/g
for (const s of fs.readdirSync(src)) {
const srcFile = path.join(src, s)
let copy = true
switch (path.extname(s)) {
case '.html': {
// Find all of the scripts that we need
const html = fs.readFileSync(srcFile, 'utf8')
let match = null
while ((match = script.exec(html))) {
needed.add(match[1])
copy = false
transform.add(s)
}
break
}
case '.js':
// Keep track of the ones we already have
have.add(s)
break
}
if (copy) {
console.log(`Copy: ${s}`)
fs.copyFileSync(srcFile, path.join(dist, s))
}
}
const scripts = new Set([...needed].filter(x => !have.has(x)))
// Find the scripts we don't have yet. Assume each one is
// a single file.
const scriptNames = {}
for (const s of scripts) {
const scriptSrc = bresolve.sync(s, {filename: __filename})
const local = path.basename(scriptSrc)
scriptNames[s] = local
console.log(`Resolve: ${s} (${path.relative(__dirname, scriptSrc)})`)
fs.copyFileSync(scriptSrc, path.join(dist, local))
}
for (const s of transform) {
const srcFile = path.join(src, s)
let html = fs.readFileSync(srcFile, 'utf8')
html = html.replace(script, (m, orig) => {
const local = scriptNames[orig]
return local ? `<script src="${local}"` : m
})
console.log(`Transform: ${s}`)
fs.writeFileSync(path.join(dist, s), html, 'utf8')
}