NamedModuleIdsPlugin.js
1.8 KB
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
61
62
63
64
65
66
67
68
69
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { compareModulesByIdentifier } = require("../util/comparators");
const {
getShortModuleName,
getLongModuleName,
assignNames,
getUsedModuleIdsAndModules,
assignAscendingModuleIds
} = require("./IdHelpers");
/** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */
/** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../Module")} Module */
/**
* @typedef {Object} NamedModuleIdsPluginOptions
* @property {string} [context] context
*/
class NamedModuleIdsPlugin {
/**
* @param {NamedModuleIdsPluginOptions} [options] options
*/
constructor(options = {}) {
this.options = options;
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const { root } = compiler;
compiler.hooks.compilation.tap("NamedModuleIdsPlugin", compilation => {
const hashFunction =
/** @type {NonNullable<Output["hashFunction"]>} */
(compilation.outputOptions.hashFunction);
compilation.hooks.moduleIds.tap("NamedModuleIdsPlugin", () => {
const chunkGraph = compilation.chunkGraph;
const context = this.options.context
? this.options.context
: compiler.context;
const [usedIds, modules] = getUsedModuleIdsAndModules(compilation);
const unnamedModules = assignNames(
modules,
m => getShortModuleName(m, context, root),
(m, shortName) =>
getLongModuleName(shortName, m, context, hashFunction, root),
compareModulesByIdentifier,
usedIds,
(m, name) => chunkGraph.setModuleId(m, name)
);
if (unnamedModules.length > 0) {
assignAscendingModuleIds(usedIds, unnamedModules, compilation);
}
});
});
}
}
module.exports = NamedModuleIdsPlugin;