ContextDependencyTemplateAsRequireCall.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const ContextDependency = require("./ContextDependency");
  7. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  8. /** @typedef {import("../Dependency")} Dependency */
  9. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  10. class ContextDependencyTemplateAsRequireCall extends ContextDependency.Template {
  11. /**
  12. * @param {Dependency} dependency the dependency for which the template should be applied
  13. * @param {ReplaceSource} source the current replace source which can be modified
  14. * @param {DependencyTemplateContext} templateContext the context object
  15. * @returns {void}
  16. */
  17. apply(
  18. dependency,
  19. source,
  20. { runtimeTemplate, moduleGraph, chunkGraph, runtimeRequirements }
  21. ) {
  22. const dep = /** @type {ContextDependency} */ (dependency);
  23. let moduleExports = runtimeTemplate.moduleExports({
  24. module: moduleGraph.getModule(dep),
  25. chunkGraph,
  26. request: dep.request,
  27. runtimeRequirements
  28. });
  29. if (dep.inShorthand) {
  30. moduleExports = `${dep.inShorthand}: ${moduleExports}`;
  31. }
  32. if (moduleGraph.getModule(dep)) {
  33. if (dep.valueRange) {
  34. if (Array.isArray(dep.replaces)) {
  35. for (let i = 0; i < dep.replaces.length; i++) {
  36. const rep = dep.replaces[i];
  37. source.replace(rep.range[0], rep.range[1] - 1, rep.value);
  38. }
  39. }
  40. source.replace(dep.valueRange[1], dep.range[1] - 1, ")");
  41. source.replace(
  42. dep.range[0],
  43. dep.valueRange[0] - 1,
  44. `${moduleExports}(`
  45. );
  46. } else {
  47. source.replace(dep.range[0], dep.range[1] - 1, moduleExports);
  48. }
  49. } else {
  50. source.replace(dep.range[0], dep.range[1] - 1, moduleExports);
  51. }
  52. }
  53. }
  54. module.exports = ContextDependencyTemplateAsRequireCall;