You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.0 KiB

4 years ago
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { ConcatSource } = require("webpack-sources");
  7. /** @typedef {import("../ChunkTemplate")} ChunkTemplate */
  8. const getEntryInfo = chunk => {
  9. return [chunk.entryModule].filter(Boolean).map(m =>
  10. [m.id].concat(
  11. Array.from(chunk.groupsIterable)[0]
  12. .chunks.filter(c => c !== chunk)
  13. .map(c => c.id)
  14. )
  15. );
  16. };
  17. class JsonpChunkTemplatePlugin {
  18. /**
  19. * @param {ChunkTemplate} chunkTemplate the chunk template
  20. * @returns {void}
  21. */
  22. apply(chunkTemplate) {
  23. chunkTemplate.hooks.render.tap(
  24. "JsonpChunkTemplatePlugin",
  25. (modules, chunk) => {
  26. const jsonpFunction = chunkTemplate.outputOptions.jsonpFunction;
  27. const globalObject = chunkTemplate.outputOptions.globalObject;
  28. const source = new ConcatSource();
  29. const prefetchChunks = chunk.getChildIdsByOrders().prefetch;
  30. source.add(
  31. `(${globalObject}[${JSON.stringify(
  32. jsonpFunction
  33. )}] = ${globalObject}[${JSON.stringify(
  34. jsonpFunction
  35. )}] || []).push([${JSON.stringify(chunk.ids)},`
  36. );
  37. source.add(modules);
  38. const entries = getEntryInfo(chunk);
  39. if (entries.length > 0) {
  40. source.add(`,${JSON.stringify(entries)}`);
  41. } else if (prefetchChunks && prefetchChunks.length) {
  42. source.add(`,0`);
  43. }
  44. if (prefetchChunks && prefetchChunks.length) {
  45. source.add(`,${JSON.stringify(prefetchChunks)}`);
  46. }
  47. source.add("])");
  48. return source;
  49. }
  50. );
  51. chunkTemplate.hooks.hash.tap("JsonpChunkTemplatePlugin", hash => {
  52. hash.update("JsonpChunkTemplatePlugin");
  53. hash.update("4");
  54. hash.update(`${chunkTemplate.outputOptions.jsonpFunction}`);
  55. hash.update(`${chunkTemplate.outputOptions.globalObject}`);
  56. });
  57. chunkTemplate.hooks.hashForChunk.tap(
  58. "JsonpChunkTemplatePlugin",
  59. (hash, chunk) => {
  60. hash.update(JSON.stringify(getEntryInfo(chunk)));
  61. hash.update(JSON.stringify(chunk.getChildIdsByOrders().prefetch) || "");
  62. }
  63. );
  64. }
  65. }
  66. module.exports = JsonpChunkTemplatePlugin;