NamedChunkIdsPlugin.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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("../../declarations/WebpackOptions").OutputNormalized} Output */
  15. /** @typedef {import("../Chunk")} Chunk */
  16. /** @typedef {import("../Compiler")} Compiler */
  17. /** @typedef {import("../Module")} Module */
  18. /**
  19. * @typedef {object} NamedChunkIdsPluginOptions
  20. * @property {string} [context] context
  21. * @property {string} [delimiter] delimiter
  22. */
  23. class NamedChunkIdsPlugin {
  24. /**
  25. * @param {NamedChunkIdsPluginOptions=} options options
  26. */
  27. constructor(options) {
  28. this.delimiter = (options && options.delimiter) || "-";
  29. this.context = options && options.context;
  30. }
  31. /**
  32. * Apply the plugin
  33. * @param {Compiler} compiler the compiler instance
  34. * @returns {void}
  35. */
  36. apply(compiler) {
  37. compiler.hooks.compilation.tap("NamedChunkIdsPlugin", compilation => {
  38. const hashFunction =
  39. /** @type {NonNullable<Output["hashFunction"]>} */
  40. (compilation.outputOptions.hashFunction);
  41. compilation.hooks.chunkIds.tap("NamedChunkIdsPlugin", chunks => {
  42. const chunkGraph = compilation.chunkGraph;
  43. const context = this.context ? this.context : compiler.context;
  44. const delimiter = this.delimiter;
  45. const unnamedChunks = assignNames(
  46. Array.from(chunks).filter(chunk => {
  47. if (chunk.name) {
  48. chunk.id = chunk.name;
  49. chunk.ids = [chunk.name];
  50. }
  51. return chunk.id === null;
  52. }),
  53. chunk =>
  54. getShortChunkName(
  55. chunk,
  56. chunkGraph,
  57. context,
  58. delimiter,
  59. hashFunction,
  60. compiler.root
  61. ),
  62. chunk =>
  63. getLongChunkName(
  64. chunk,
  65. chunkGraph,
  66. context,
  67. delimiter,
  68. hashFunction,
  69. compiler.root
  70. ),
  71. compareChunksNatural(chunkGraph),
  72. getUsedChunkIds(compilation),
  73. (chunk, name) => {
  74. chunk.id = name;
  75. chunk.ids = [name];
  76. }
  77. );
  78. if (unnamedChunks.length > 0) {
  79. assignAscendingChunkIds(unnamedChunks, compilation);
  80. }
  81. });
  82. });
  83. }
  84. }
  85. module.exports = NamedChunkIdsPlugin;