NamedChunkIdsPlugin.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. assignAscendingChunkIds,
  9. assignNames,
  10. getLongChunkName,
  11. getShortChunkName,
  12. getUsedChunkIds
  13. } = require("./IdHelpers");
  14. /** @typedef {import("../Compiler")} Compiler */
  15. /**
  16. * Defines the named chunk ids plugin options type used by this module.
  17. * @typedef {object} NamedChunkIdsPluginOptions
  18. * @property {string=} context context
  19. * @property {string=} delimiter delimiter
  20. */
  21. const PLUGIN_NAME = "NamedChunkIdsPlugin";
  22. class NamedChunkIdsPlugin {
  23. /**
  24. * Creates an instance of NamedChunkIdsPlugin.
  25. * @param {NamedChunkIdsPluginOptions=} options options
  26. */
  27. constructor(options = {}) {
  28. /** @type {NamedChunkIdsPluginOptions} */
  29. this.options = options;
  30. }
  31. /**
  32. * Applies the plugin by registering its hooks on the compiler.
  33. * @param {Compiler} compiler the compiler instance
  34. * @returns {void}
  35. */
  36. apply(compiler) {
  37. compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
  38. const hashFunction = compilation.outputOptions.hashFunction;
  39. compilation.hooks.chunkIds.tap(PLUGIN_NAME, (chunks) => {
  40. const chunkGraph = compilation.chunkGraph;
  41. const context = this.options.context
  42. ? this.options.context
  43. : compiler.context;
  44. const delimiter = this.options.delimiter || "-";
  45. const unnamedChunks = assignNames(
  46. [...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;