-
Notifications
You must be signed in to change notification settings - Fork 1
/
demobuild.mjs
74 lines (59 loc) · 2.44 KB
/
demobuild.mjs
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
import fileSystem from 'fs';
const sha1Digest = async (text) => {
const encoder = new TextEncoder();
const data = encoder.encode(text);
const hash = await crypto.subtle.digest('SHA-1', data);
const hashArray = Array.from(new Uint8Array(hash));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
};
const getFileText = (path) => {
return new Promise((resolve, reject) => {
fileSystem.readFile(path, 'utf-8', (error, data) => {
if (error) {
reject(error);
}
resolve(data);
});
});
};
const writeFileText = (path, text) => {
fileSystem.writeFile(path, text, (error) => {
if (error) {
console.error(error);
}
});
};
const makeCssHash = async () => {
const cssText = await getFileText('dist/comparing-slider.min.css');
const demoCss = await getFileText('demo/index.css');
const demoHtml = await getFileText('demo/index.html');
const hash = await sha1Digest(cssText);
const demoHash = await sha1Digest(demoCss);
let regex = /@import\s*"\.\.\/dist\/comparing-slider\.min\.css\?v=([^"]+)";/g;
let replacement = '@import "../dist/comparing-slider.min.css?v=NEW_VALUE";';
let newValue = hash;
const newDemoCss = demoCss.replace(regex, replacement.replace('NEW_VALUE', newValue));
writeFileText('demo/index.css', newDemoCss);
regex = /\<link\s*rel\=\"stylesheet\"\s*href\=\"index.css\?v=([^"]+)"\>\<\/link\>/g;
replacement = '<link rel="stylesheet" href="index.css?v=NEW_VALUE"></link>';
newValue = demoHash;
const newDemoHtml = demoHtml.replace(regex, replacement.replace('NEW_VALUE', newValue));
writeFileText('demo/index.html', newDemoHtml);
};
const makeJsHash = async () => {
const jsText = await getFileText('dist/comparing-slider.min.js');
const demoHtml = await getFileText('demo/index.html');
const hash = await sha1Digest(jsText);
const regex = /\<script src\=\"\.\.\/dist\/comparing-slider\.min\.js\?v=([^"]+)"\>\<\/script\>/g;
let replacement = '<script src="../dist/comparing-slider.min.js?v=NEW_VALUE"></script>';
let newValue = hash;
const newDemoHtml = demoHtml.replace(regex, replacement.replace('NEW_VALUE', newValue));
writeFileText('demo/index.html', newDemoHtml);
};
const main = async () => {
await makeCssHash();
await makeJsHash();
};
console.time('Build time');
main();
console.timeEnd('Build time');