RequireHeaderDependency.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RuntimeGlobals = require("../RuntimeGlobals");
  7. const makeSerializable = require("../util/makeSerializable");
  8. const NullDependency = require("./NullDependency");
  9. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  10. /** @typedef {import("../Dependency")} Dependency */
  11. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  12. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  13. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  14. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  15. class RequireHeaderDependency extends NullDependency {
  16. /**
  17. * Creates an instance of RequireHeaderDependency.
  18. * @param {Range} range range
  19. */
  20. constructor(range) {
  21. super();
  22. if (!Array.isArray(range)) throw new Error("range must be valid");
  23. this.range = range;
  24. }
  25. /**
  26. * Serializes this instance into the provided serializer context.
  27. * @param {ObjectSerializerContext} context context
  28. */
  29. serialize(context) {
  30. const { write } = context;
  31. write(this.range);
  32. super.serialize(context);
  33. }
  34. /**
  35. * Restores this instance from the provided deserializer context.
  36. * @param {ObjectDeserializerContext} context context
  37. * @returns {RequireHeaderDependency} RequireHeaderDependency
  38. */
  39. static deserialize(context) {
  40. const obj = new RequireHeaderDependency(context.read());
  41. obj.deserialize(context);
  42. return obj;
  43. }
  44. }
  45. makeSerializable(
  46. RequireHeaderDependency,
  47. "webpack/lib/dependencies/RequireHeaderDependency"
  48. );
  49. RequireHeaderDependency.Template = class RequireHeaderDependencyTemplate extends (
  50. NullDependency.Template
  51. ) {
  52. /**
  53. * Applies the plugin by registering its hooks on the compiler.
  54. * @param {Dependency} dependency the dependency for which the template should be applied
  55. * @param {ReplaceSource} source the current replace source which can be modified
  56. * @param {DependencyTemplateContext} templateContext the context object
  57. * @returns {void}
  58. */
  59. apply(dependency, source, { runtimeRequirements }) {
  60. const dep = /** @type {RequireHeaderDependency} */ (dependency);
  61. runtimeRequirements.add(RuntimeGlobals.require);
  62. source.replace(dep.range[0], dep.range[1] - 1, RuntimeGlobals.require);
  63. }
  64. };
  65. module.exports = RequireHeaderDependency;