-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
60 lines (51 loc) · 1.58 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
"use strict";
const createHash = require("webpack/lib/util/createHash");
const fs = require('fs');
class ContentHashedModuleIdsPlugin {
constructor(options) {
if (!options) options = {};
this.options = Object.assign(
{
context: null,
hashFunction: "md4",
hashDigest: "base64",
hashDigestLength: 10
},
options
);
}
apply(compiler) {
const options = this.options;
compiler.hooks.compilation.tap("ContentHashedModuleIdsPlugin", compilation => {
const usedIds = new Set();
compilation.hooks.beforeModuleIds.tap(
"ContentHashedModuleIdsPlugin",
(modules) => {
for (const module of modules) {
if (module.id === null && module.resource) {
const hash = createHash(options.hashFunction);
let resourcePath = module.resource;
if (resourcePath.indexOf('?') > -1) {
resourcePath = resourcePath.split('?')[0];
}
try {
hash.update(fs.readFileSync(resourcePath));
} catch (ex) {
console.error('failed on', module.context, module.resource);
throw ex;
}
const hashId = hash.digest(options.hashDigest);
let len = options.hashDigestLength;
while (usedIds.has(hashId.substr(0, len))) {
len++;
}
module.id = hashId.substr(0, len);
usedIds.add(module.id);
}
}
}
);
});
}
}
module.exports = ContentHashedModuleIdsPlugin;