UNPKG

3.03 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Florent Cailhol @ooflorent
4*/
5
6"use strict";
7
8const {
9 compareModulesByPreOrderIndexOrIdentifier
10} = require("../util/comparators");
11const {
12 getUsedModuleIdsAndModules,
13 getFullModuleName,
14 assignDeterministicIds
15} = require("./IdHelpers");
16
17/** @typedef {import("../Compiler")} Compiler */
18/** @typedef {import("../Module")} Module */
19
20class DeterministicModuleIdsPlugin {
21 /**
22 * @param {Object} options options
23 * @param {string=} options.context context relative to which module identifiers are computed
24 * @param {function(Module): boolean=} options.test selector function for modules
25 * @param {number=} options.maxLength maximum id length in digits (used as starting point)
26 * @param {number=} options.salt hash salt for ids
27 * @param {boolean=} options.fixedLength do not increase the maxLength to find an optimal id space size
28 * @param {boolean=} options.failOnConflict throw an error when id conflicts occur (instead of rehashing)
29 */
30 constructor(options = {}) {
31 this.options = options;
32 }
33
34 /**
35 * Apply the plugin
36 * @param {Compiler} compiler the compiler instance
37 * @returns {void}
38 */
39 apply(compiler) {
40 compiler.hooks.compilation.tap(
41 "DeterministicModuleIdsPlugin",
42 compilation => {
43 compilation.hooks.moduleIds.tap("DeterministicModuleIdsPlugin", () => {
44 const chunkGraph = compilation.chunkGraph;
45 const context = this.options.context
46 ? this.options.context
47 : compiler.context;
48 const maxLength = this.options.maxLength || 3;
49 const failOnConflict = this.options.failOnConflict || false;
50 const fixedLength = this.options.fixedLength || false;
51 const salt = this.options.salt || 0;
52 let conflicts = 0;
53
54 const [usedIds, modules] = getUsedModuleIdsAndModules(
55 compilation,
56 this.options.test
57 );
58 assignDeterministicIds(
59 modules,
60 module => getFullModuleName(module, context, compiler.root),
61 failOnConflict
62 ? () => 0
63 : compareModulesByPreOrderIndexOrIdentifier(
64 compilation.moduleGraph
65 ),
66 (module, id) => {
67 const size = usedIds.size;
68 usedIds.add(`${id}`);
69 if (size === usedIds.size) {
70 conflicts++;
71 return false;
72 }
73 chunkGraph.setModuleId(module, id);
74 return true;
75 },
76 [Math.pow(10, maxLength)],
77 fixedLength ? 0 : 10,
78 usedIds.size,
79 salt
80 );
81 if (failOnConflict && conflicts)
82 throw new Error(
83 `Assigning deterministic module ids has lead to ${conflicts} conflict${
84 conflicts > 1 ? "s" : ""
85 }.\nIncrease the 'maxLength' to increase the id space and make conflicts less likely (recommended when there are many conflicts or application is expected to grow), or add an 'salt' number to try another hash starting value in the same id space (recommended when there is only a single conflict).`
86 );
87 });
88 }
89 );
90 }
91}
92
93module.exports = DeterministicModuleIdsPlugin;