-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
ReplaceHashPlugin.js
56 lines (41 loc) · 1.42 KB
/
ReplaceHashPlugin.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
import { resolve } from 'path';
import { readFileSync, readdirSync, writeFileSync } from 'fs';
function ReplaceHashPlugin(options = {}) {
this.options = options;
}
ReplaceHashPlugin.prototype.apply = function (compiler) {
let done = statsData => {
if (!statsData.hasErrors())
replace(this.options, statsData.compilation.assets);
};
compiler.hooks.done.tap({ name: 'ReplaceHashPlugin' }, done);
};
function replace(options, assets) {
let hash = new Map()
hash.set('[VAPID-PUBLIC-KEY-contenthash]', process.env.VAPID_PUBLIC_KEY);
for (let key in assets) {
let splitted = key.split('.'),
extension = splitted.pop();
if (extension != 'js' && extension != 'css')
continue;
hash.set(`[${splitted[0]}-${extension}-contenthash]`, splitted[1]);
}
for (let entry of options.files) {
let fileName;
if (typeof entry === 'string')
fileName = entry;
else {
fileName = `${entry.dir}/${readdirSync(resolve(entry.dir)).find(f => f.startsWith(entry.prefix))}`;
}
replaceInFile(fileName, hash);
}
}
function replaceInFile(fileName, hash) {
let path = resolve(fileName),
contents = readFileSync(path, 'utf8');
for (let [key, value] of hash) {
contents = contents.replace(key, value);
}
writeFileSync(path, contents);
}
export default ReplaceHashPlugin;