NamedModuleIdsPlugin.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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("../Compiler")} Compiler */
  15. /** @typedef {import("../Module")} Module */
  16. class NamedModuleIdsPlugin {
  17. constructor(options) {
  18. this.options = options || {};
  19. }
  20. /**
  21. * Apply the plugin
  22. * @param {Compiler} compiler the compiler instance
  23. * @returns {void}
  24. */
  25. apply(compiler) {
  26. const { root } = compiler;
  27. compiler.hooks.compilation.tap("NamedModuleIdsPlugin", compilation => {
  28. const { hashFunction } = compilation.outputOptions;
  29. compilation.hooks.moduleIds.tap("NamedModuleIdsPlugin", () => {
  30. const chunkGraph = compilation.chunkGraph;
  31. const context = this.options.context
  32. ? this.options.context
  33. : compiler.context;
  34. const [usedIds, modules] = getUsedModuleIdsAndModules(compilation);
  35. const unnamedModules = assignNames(
  36. modules,
  37. m => getShortModuleName(m, context, root),
  38. (m, shortName) =>
  39. getLongModuleName(shortName, m, context, hashFunction, root),
  40. compareModulesByIdentifier,
  41. usedIds,
  42. (m, name) => chunkGraph.setModuleId(m, name)
  43. );
  44. if (unnamedModules.length > 0) {
  45. assignAscendingModuleIds(usedIds, unnamedModules, compilation);
  46. }
  47. });
  48. });
  49. }
  50. }
  51. module.exports = NamedModuleIdsPlugin;