GlobalRuntimeModule.js 1.8 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 RuntimeModule = require("../RuntimeModule");
  7. const Template = require("../Template");
  8. /** @typedef {import("../Compilation")} Compilation */
  9. class GlobalRuntimeModule extends RuntimeModule {
  10. constructor() {
  11. super("global");
  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. // `environment.globalThis` promises the binding is there, so nothing has to
  29. // be searched for.
  30. if (compilation.outputOptions.environment.globalThis) {
  31. return `${RuntimeGlobals.global} = globalThis;`;
  32. }
  33. return Template.asString([
  34. `${RuntimeGlobals.global} = (function() {`,
  35. Template.indent([
  36. "if (typeof globalThis === 'object') return globalThis;",
  37. "try {",
  38. Template.indent(
  39. // This works in non-strict mode
  40. // or
  41. // This works if eval is allowed (see CSP)
  42. "return this || new Function('return this')();"
  43. ),
  44. "} catch (e) {",
  45. Template.indent(
  46. // This works if the window reference is available
  47. "if (typeof window === 'object') return window;"
  48. ),
  49. "}"
  50. // It can still be `undefined`, but nothing to do about it...
  51. // We return `undefined`, instead of nothing here, so it's
  52. // easier to handle this case:
  53. // if (!global) { … }
  54. ]),
  55. "})();"
  56. ]);
  57. }
  58. }
  59. module.exports = GlobalRuntimeModule;