AmdMainTemplatePlugin.js 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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").ConcatSource;
  7. const Template = require("./Template");
  8. class AmdMainTemplatePlugin {
  9. constructor(name) {
  10. this.name = name;
  11. }
  12. apply(compilation) {
  13. const mainTemplate = compilation.mainTemplate;
  14. compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
  15. const externals = chunk.getModules().filter((m) => m.external);
  16. const externalsDepsArray = JSON.stringify(externals.map((m) =>
  17. typeof m.request === "object" ? m.request.amd : m.request
  18. ));
  19. const externalsArguments = externals.map((m) =>
  20. Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${m.id}__`)
  21. ).join(", ");
  22. if(this.name) {
  23. const name = mainTemplate.applyPluginsWaterfall("asset-path", this.name, {
  24. hash,
  25. chunk
  26. });
  27. return new ConcatSource(
  28. `define(${JSON.stringify(name)}, ${externalsDepsArray}, function(${externalsArguments}) { return `, source, "});"
  29. );
  30. } else if(externalsArguments) {
  31. return new ConcatSource(`define(${externalsDepsArray}, function(${externalsArguments}) { return `, source, "});");
  32. } else {
  33. return new ConcatSource("define(function() { return ", source, "});");
  34. }
  35. });
  36. mainTemplate.plugin("global-hash-paths", (paths) => {
  37. if(this.name) paths.push(this.name);
  38. return paths;
  39. });
  40. mainTemplate.plugin("hash", (hash) => {
  41. hash.update("exports amd");
  42. hash.update(this.name);
  43. });
  44. }
  45. }
  46. module.exports = AmdMainTemplatePlugin;