-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathwebpack-asset-tracker.js
48 lines (45 loc) · 1.67 KB
/
webpack-asset-tracker.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
const fs = require('fs');
const path = require('path');
const R = require('ramda');
const crypto = require('crypto');
const name = 'BundleTracker';
const plugin = ({path: output, filename, integrity, algorithm = 'sha384'}) => ({
apply: compiler => {
compiler.hooks.done.tap(name, (stats, ...args) => {
if (stats.hasErrors()) return;
const assets = R.reduce(
(acc, chunkGroup) => {
const files = chunkGroup.getFiles();
acc[chunkGroup.name] = R.map((file) => {
const asset = {name: file};
if (integrity) {
const fileContent = fs.readFileSync(
path.join(
output,
file
)
);
const hash = crypto
.createHash(algorithm)
.update(fileContent, 'utf8')
.digest('base64');
asset.integrity = `${algorithm}-${hash}`
}
return asset;
}, files);
return acc;
},
{},
stats.compilation.chunkGroups
);
fs.writeFile(
path.join(output, filename),
JSON.stringify(assets),
err => {
if (err) process.stderr.write(`BundleTrackerError: ${err}`);
}
);
});
},
});
module.exports = plugin;