NamedModuleIdsPlugin.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { compareModulesByIdentifier } = require("../util/comparators");
  7. const {
  8. getShortModuleName,
  9. getLongModuleName,
  10. assignNames,
  11. getUsedModuleIdsAndModules,
  12. assignAscendingModuleIds
  13. } = require("./IdHelpers");
  14. /** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */
  15. /** @typedef {import("../Compiler")} Compiler */
  16. /** @typedef {import("../Module")} Module */
  17. /**
  18. * @typedef {object} NamedModuleIdsPluginOptions
  19. * @property {string} [context] context
  20. */
  21. class NamedModuleIdsPlugin {
  22. /**
  23. * @param {NamedModuleIdsPluginOptions} [options] options
  24. */
  25. constructor(options = {}) {
  26. this.options = options;
  27. }
  28. /**
  29. * Apply the plugin
  30. * @param {Compiler} compiler the compiler instance
  31. * @returns {void}
  32. */
  33. apply(compiler) {
  34. const { root } = compiler;
  35. compiler.hooks.compilation.tap("NamedModuleIdsPlugin", compilation => {
  36. const hashFunction =
  37. /** @type {NonNullable<Output["hashFunction"]>} */
  38. (compilation.outputOptions.hashFunction);
  39. compilation.hooks.moduleIds.tap("NamedModuleIdsPlugin", () => {
  40. const chunkGraph = compilation.chunkGraph;
  41. const context = this.options.context
  42. ? this.options.context
  43. : compiler.context;
  44. const [usedIds, modules] = getUsedModuleIdsAndModules(compilation);
  45. const unnamedModules = assignNames(
  46. modules,
  47. m => getShortModuleName(m, context, root),
  48. (m, shortName) =>
  49. getLongModuleName(shortName, m, context, hashFunction, root),
  50. compareModulesByIdentifier,
  51. usedIds,
  52. (m, name) => chunkGraph.setModuleId(m, name)
  53. );
  54. if (unnamedModules.length > 0) {
  55. assignAscendingModuleIds(usedIds, unnamedModules, compilation);
  56. }
  57. });
  58. });
  59. }
  60. }
  61. module.exports = NamedModuleIdsPlugin;