LocalModuleDependency.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const makeSerializable = require("../util/makeSerializable");
  7. const NullDependency = require("./NullDependency");
  8. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  9. /** @typedef {import("../Dependency")} Dependency */
  10. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  11. class LocalModuleDependency extends NullDependency {
  12. constructor(localModule, range, callNew) {
  13. super();
  14. this.localModule = localModule;
  15. this.range = range;
  16. this.callNew = callNew;
  17. }
  18. serialize(context) {
  19. const { write } = context;
  20. write(this.localModule);
  21. write(this.range);
  22. write(this.callNew);
  23. super.serialize(context);
  24. }
  25. deserialize(context) {
  26. const { read } = context;
  27. this.localModule = read();
  28. this.range = read();
  29. this.callNew = read();
  30. super.deserialize(context);
  31. }
  32. }
  33. makeSerializable(
  34. LocalModuleDependency,
  35. "webpack/lib/dependencies/LocalModuleDependency"
  36. );
  37. LocalModuleDependency.Template = class LocalModuleDependencyTemplate extends (
  38. NullDependency.Template
  39. ) {
  40. /**
  41. * @param {Dependency} dependency the dependency for which the template should be applied
  42. * @param {ReplaceSource} source the current replace source which can be modified
  43. * @param {DependencyTemplateContext} templateContext the context object
  44. * @returns {void}
  45. */
  46. apply(dependency, source, templateContext) {
  47. const dep = /** @type {LocalModuleDependency} */ (dependency);
  48. if (!dep.range) return;
  49. const moduleInstance = dep.callNew
  50. ? `new (function () { return ${dep.localModule.variableName()}; })()`
  51. : dep.localModule.variableName();
  52. source.replace(dep.range[0], dep.range[1] - 1, moduleInstance);
  53. }
  54. };
  55. module.exports = LocalModuleDependency;