123456789101112131415161718192021222324252627282930313233343536373839404142
  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. class SetVarMainTemplatePlugin {
  8. constructor(varExpression, copyObject) {
  9. this.varExpression = varExpression;
  10. this.copyObject = copyObject;
  11. }
  12. apply(compilation) {
  13. const mainTemplate = compilation.mainTemplate;
  14. compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
  15. const varExpression = mainTemplate.applyPluginsWaterfall("asset-path", this.varExpression, {
  16. hash,
  17. chunk
  18. });
  19. if(this.copyObject) {
  20. return new ConcatSource(`(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `, source, "))");
  21. } else {
  22. const prefix = `${varExpression} =\n`;
  23. return new ConcatSource(prefix, source);
  24. }
  25. });
  26. mainTemplate.plugin("global-hash-paths", (paths) => {
  27. if(this.varExpression) paths.push(this.varExpression);
  28. return paths;
  29. });
  30. mainTemplate.plugin("hash", hash => {
  31. hash.update("set var");
  32. hash.update(`${this.varExpression}`);
  33. hash.update(`${this.copyObject}`);
  34. });
  35. }
  36. }
  37. module.exports = SetVarMainTemplatePlugin;