NamedChunkIdsPlugin.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { compareChunksNatural } = require("../util/comparators");
  7. const {
  8. getShortChunkName,
  9. getLongChunkName,
  10. assignNames,
  11. getUsedChunkIds,
  12. assignAscendingChunkIds
  13. } = require("./IdHelpers");
  14. /** @typedef {import("../Chunk")} Chunk */
  15. /** @typedef {import("../Compiler")} Compiler */
  16. /** @typedef {import("../Module")} Module */
  17. class NamedChunkIdsPlugin {
  18. constructor(options) {
  19. this.delimiter = (options && options.delimiter) || "-";
  20. this.context = options && options.context;
  21. }
  22. /**
  23. * Apply the plugin
  24. * @param {Compiler} compiler the compiler instance
  25. * @returns {void}
  26. */
  27. apply(compiler) {
  28. compiler.hooks.compilation.tap("NamedChunkIdsPlugin", compilation => {
  29. const { hashFunction } = compilation.outputOptions;
  30. compilation.hooks.chunkIds.tap("NamedChunkIdsPlugin", chunks => {
  31. const chunkGraph = compilation.chunkGraph;
  32. const context = this.context ? this.context : compiler.context;
  33. const delimiter = this.delimiter;
  34. const unnamedChunks = assignNames(
  35. Array.from(chunks).filter(chunk => {
  36. if (chunk.name) {
  37. chunk.id = chunk.name;
  38. chunk.ids = [chunk.name];
  39. }
  40. return chunk.id === null;
  41. }),
  42. chunk =>
  43. getShortChunkName(
  44. chunk,
  45. chunkGraph,
  46. context,
  47. delimiter,
  48. hashFunction,
  49. compiler.root
  50. ),
  51. chunk =>
  52. getLongChunkName(
  53. chunk,
  54. chunkGraph,
  55. context,
  56. delimiter,
  57. hashFunction,
  58. compiler.root
  59. ),
  60. compareChunksNatural(chunkGraph),
  61. getUsedChunkIds(compilation),
  62. (chunk, name) => {
  63. chunk.id = name;
  64. chunk.ids = [name];
  65. }
  66. );
  67. if (unnamedChunks.length > 0) {
  68. assignAscendingChunkIds(unnamedChunks, compilation);
  69. }
  70. });
  71. });
  72. }
  73. }
  74. module.exports = NamedChunkIdsPlugin;