NamedChunkIdsPlugin.js 2.1 KB

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