CreateFakeNamespaceObjectRuntimeModule.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. class CreateFakeNamespaceObjectRuntimeModule extends HelperRuntimeModule {
  9. constructor() {
  10. super("create fake namespace object");
  11. }
  12. /**
  13. * @returns {string} runtime code
  14. */
  15. generate() {
  16. const { runtimeTemplate } = this.compilation;
  17. const fn = RuntimeGlobals.createFakeNamespaceObject;
  18. return Template.asString([
  19. `var getProto = Object.getPrototypeOf ? ${runtimeTemplate.returningFunction(
  20. "Object.getPrototypeOf(obj)",
  21. "obj"
  22. )} : ${runtimeTemplate.returningFunction("obj.__proto__", "obj")};`,
  23. "var leafPrototypes;",
  24. "// create a fake namespace object",
  25. "// mode & 1: value is a module id, require it",
  26. "// mode & 2: merge all properties of value into the ns",
  27. "// mode & 4: return value when already ns object",
  28. "// mode & 16: return value when it's Promise-like",
  29. "// mode & 8|1: behave like require",
  30. // Note: must be a function (not arrow), because this is used in body!
  31. `${fn} = function(value, mode) {`,
  32. Template.indent([
  33. `if(mode & 1) value = this(value);`,
  34. `if(mode & 8) return value;`,
  35. "if(typeof value === 'object' && value) {",
  36. Template.indent([
  37. "if((mode & 4) && value.__esModule) return value;",
  38. "if((mode & 16) && typeof value.then === 'function') return value;"
  39. ]),
  40. "}",
  41. "var ns = Object.create(null);",
  42. `${RuntimeGlobals.makeNamespaceObject}(ns);`,
  43. "var def = {};",
  44. "leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];",
  45. "for(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {",
  46. Template.indent([
  47. `Object.getOwnPropertyNames(current).forEach(${runtimeTemplate.expressionFunction(
  48. `def[key] = ${runtimeTemplate.returningFunction("value[key]", "")}`,
  49. "key"
  50. )});`
  51. ]),
  52. "}",
  53. `def['default'] = ${runtimeTemplate.returningFunction("value", "")};`,
  54. `${RuntimeGlobals.definePropertyGetters}(ns, def);`,
  55. "return ns;"
  56. ]),
  57. "};"
  58. ]);
  59. }
  60. }
  61. module.exports = CreateFakeNamespaceObjectRuntimeModule;