1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 | const {
|
9 | compareModulesByPreOrderIndexOrIdentifier
|
10 | } = require("../util/comparators");
|
11 | const createSchemaValidation = require("../util/create-schema-validation");
|
12 | const createHash = require("../util/createHash");
|
13 | const { getUsedModuleIds, getFullModuleName } = require("./IdHelpers");
|
14 |
|
15 |
|
16 |
|
17 | const validate = createSchemaValidation(
|
18 | require("../../schemas/plugins/HashedModuleIdsPlugin.check.js"),
|
19 | () => require("../../schemas/plugins/HashedModuleIdsPlugin.json"),
|
20 | {
|
21 | name: "Hashed Module Ids Plugin",
|
22 | baseDataPath: "options"
|
23 | }
|
24 | );
|
25 |
|
26 | class HashedModuleIdsPlugin {
|
27 | |
28 |
|
29 |
|
30 | constructor(options = {}) {
|
31 | validate(options);
|
32 |
|
33 |
|
34 | this.options = {
|
35 | context: null,
|
36 | hashFunction: "md4",
|
37 | hashDigest: "base64",
|
38 | hashDigestLength: 4,
|
39 | ...options
|
40 | };
|
41 | }
|
42 |
|
43 | apply(compiler) {
|
44 | const options = this.options;
|
45 | compiler.hooks.compilation.tap("HashedModuleIdsPlugin", compilation => {
|
46 | compilation.hooks.moduleIds.tap("HashedModuleIdsPlugin", modules => {
|
47 | const chunkGraph = compilation.chunkGraph;
|
48 | const context = this.options.context
|
49 | ? this.options.context
|
50 | : compiler.context;
|
51 |
|
52 | const usedIds = getUsedModuleIds(compilation);
|
53 | const modulesInNaturalOrder = Array.from(modules)
|
54 | .filter(m => {
|
55 | if (!m.needId) return false;
|
56 | if (chunkGraph.getNumberOfModuleChunks(m) === 0) return false;
|
57 | return chunkGraph.getModuleId(module) === null;
|
58 | })
|
59 | .sort(
|
60 | compareModulesByPreOrderIndexOrIdentifier(compilation.moduleGraph)
|
61 | );
|
62 | for (const module of modulesInNaturalOrder) {
|
63 | const ident = getFullModuleName(module, context, compiler.root);
|
64 | const hash = createHash(options.hashFunction);
|
65 | hash.update(ident || "");
|
66 | const hashId = (
|
67 | hash.digest(options.hashDigest)
|
68 | );
|
69 | let len = options.hashDigestLength;
|
70 | while (usedIds.has(hashId.substr(0, len))) len++;
|
71 | const moduleId = hashId.substr(0, len);
|
72 | chunkGraph.setModuleId(module, moduleId);
|
73 | usedIds.add(moduleId);
|
74 | }
|
75 | });
|
76 | });
|
77 | }
|
78 | }
|
79 |
|
80 | module.exports = HashedModuleIdsPlugin;
|