RuntimeChunkPlugin.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. /** @typedef {import("../Compilation").EntryData} EntryData */
  7. /** @typedef {import("../Compiler")} Compiler */
  8. const PLUGIN_NAME = "RuntimeChunkPlugin";
  9. /** @typedef {(entrypoint: { name: string }) => string} RuntimeChunkFunction */
  10. class RuntimeChunkPlugin {
  11. /**
  12. * Creates an instance of RuntimeChunkPlugin.
  13. * @param {{ name?: RuntimeChunkFunction }=} options options
  14. */
  15. constructor(options = {}) {
  16. /** @type {{ name: string | RuntimeChunkFunction }} */
  17. this.options = {
  18. name: (entrypoint) => `runtime~${entrypoint.name}`,
  19. ...options
  20. };
  21. }
  22. /**
  23. * Applies the plugin by registering its hooks on the compiler.
  24. * @param {Compiler} compiler the compiler instance
  25. * @returns {void}
  26. */
  27. apply(compiler) {
  28. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
  29. compilation.hooks.addEntry.tap(PLUGIN_NAME, (_, { name: entryName }) => {
  30. if (entryName === undefined) return;
  31. const data =
  32. /** @type {EntryData} */
  33. (compilation.entries.get(entryName));
  34. if (data.options.runtime === undefined && !data.options.dependOn) {
  35. // Determine runtime chunk name
  36. let name = this.options.name;
  37. if (typeof name === "function") {
  38. name = name({ name: entryName });
  39. }
  40. data.options.runtime = name;
  41. }
  42. });
  43. });
  44. }
  45. }
  46. module.exports = RuntimeChunkPlugin;