NamedChunkIdsPlugin.js 2.3 KB

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