AmdMainTemplatePlugin.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. const Template = require("./Template");
  8. /** @typedef {import("./Compilation")} Compilation */
  9. class AmdMainTemplatePlugin {
  10. /**
  11. * @param {string} name the library name
  12. */
  13. constructor(name) {
  14. /** @type {string} */
  15. this.name = name;
  16. }
  17. /**
  18. * @param {Compilation} compilation the compilation instance
  19. * @returns {void}
  20. */
  21. apply(compilation) {
  22. const { mainTemplate, chunkTemplate } = compilation;
  23. const onRenderWithEntry = (source, chunk, hash) => {
  24. const externals = chunk.getModules().filter(m => m.external);
  25. const externalsDepsArray = JSON.stringify(
  26. externals.map(
  27. m => (typeof m.request === "object" ? m.request.amd : m.request)
  28. )
  29. );
  30. const externalsArguments = externals
  31. .map(
  32. m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__`
  33. )
  34. .join(", ");
  35. if (this.name) {
  36. const name = mainTemplate.getAssetPath(this.name, {
  37. hash,
  38. chunk
  39. });
  40. return new ConcatSource(
  41. `define(${JSON.stringify(
  42. name
  43. )}, ${externalsDepsArray}, function(${externalsArguments}) { return `,
  44. source,
  45. "});"
  46. );
  47. } else if (externalsArguments) {
  48. return new ConcatSource(
  49. `define(${externalsDepsArray}, function(${externalsArguments}) { return `,
  50. source,
  51. "});"
  52. );
  53. } else {
  54. return new ConcatSource("define(function() { return ", source, "});");
  55. }
  56. };
  57. for (const template of [mainTemplate, chunkTemplate]) {
  58. template.hooks.renderWithEntry.tap(
  59. "AmdMainTemplatePlugin",
  60. onRenderWithEntry
  61. );
  62. }
  63. mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => {
  64. if (this.name) {
  65. paths.push(this.name);
  66. }
  67. return paths;
  68. });
  69. mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => {
  70. hash.update("exports amd");
  71. hash.update(this.name);
  72. });
  73. }
  74. }
  75. module.exports = AmdMainTemplatePlugin;