ConstructRequireRuntimeModule.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const RuntimeGlobals = require("../RuntimeGlobals");
  6. const Template = require("../Template");
  7. const HelperRuntimeModule = require("./HelperRuntimeModule");
  8. /** @import Compilation from "../Compilation" */
  9. class ConstructRequireRuntimeModule extends HelperRuntimeModule {
  10. constructor() {
  11. super("construct require");
  12. }
  13. /**
  14. * Returns true, if the runtime module should get it's own scope.
  15. * When false, `generate()` must emit complete statements ending with `;`
  16. * so a following runtime IIFE is not parsed as a call (ASI).
  17. * @returns {boolean} true, if the runtime module should get it's own scope
  18. */
  19. shouldIsolate() {
  20. return false;
  21. }
  22. /**
  23. * Generates runtime code for this runtime module.
  24. * @returns {string | null} runtime code
  25. */
  26. generate() {
  27. const compilation = /** @type {Compilation} */ (this.compilation);
  28. const { runtimeTemplate } = compilation;
  29. const fn = RuntimeGlobals.constructRequire;
  30. return Template.asString([
  31. "// `new require(id)` invokes the require function as a constructor, so a",
  32. "// primitive module.exports is discarded in favor of the freshly created",
  33. "// instance, exactly as in Node.js. A concatenated module has no require",
  34. "// call left, so apply that rule to its exports value instead.",
  35. `${fn} = ${runtimeTemplate.basicFunction("exports", [
  36. `${runtimeTemplate.renderConst()} isObject =`,
  37. Template.indent(
  38. 'exports !== null && (typeof exports === "object" || typeof exports === "function");'
  39. ),
  40. `return isObject ? exports : Object.create(${RuntimeGlobals.require}.prototype);`
  41. ])};`
  42. ]);
  43. }
  44. }
  45. module.exports = ConstructRequireRuntimeModule;