ContextDependencyTemplateAsId.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 ContextDependencyTemplateAsId 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. const moduleExports = runtimeTemplate.moduleExports({
  24. module: moduleGraph.getModule(dep),
  25. chunkGraph,
  26. request: dep.request,
  27. weak: dep.weak,
  28. runtimeRequirements
  29. });
  30. if (moduleGraph.getModule(dep)) {
  31. if (dep.valueRange) {
  32. if (Array.isArray(dep.replaces)) {
  33. for (let i = 0; i < dep.replaces.length; i++) {
  34. const rep = dep.replaces[i];
  35. source.replace(rep.range[0], rep.range[1] - 1, rep.value);
  36. }
  37. }
  38. source.replace(dep.valueRange[1], dep.range[1] - 1, ")");
  39. source.replace(
  40. dep.range[0],
  41. dep.valueRange[0] - 1,
  42. `${moduleExports}.resolve(`
  43. );
  44. } else {
  45. source.replace(
  46. dep.range[0],
  47. dep.range[1] - 1,
  48. `${moduleExports}.resolve`
  49. );
  50. }
  51. } else {
  52. source.replace(dep.range[0], dep.range[1] - 1, moduleExports);
  53. }
  54. }
  55. }
  56. module.exports = ContextDependencyTemplateAsId;