WorkerRuntimeModule.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const RuntimeGlobals = require("../RuntimeGlobals");
  6. const HelperRuntimeModule = require("./HelperRuntimeModule");
  7. /** @import Compilation from "../Compilation" */
  8. class WorkerRuntimeModule extends HelperRuntimeModule {
  9. constructor() {
  10. super("worker");
  11. }
  12. /**
  13. * Returns true, if the runtime module should get it's own scope.
  14. * When false, `generate()` must emit complete statements ending with `;`
  15. * so a following runtime IIFE is not parsed as a call (ASI).
  16. * @returns {boolean} true, if the runtime module should get it's own scope
  17. */
  18. shouldIsolate() {
  19. return false;
  20. }
  21. /**
  22. * Generates runtime code for this runtime module.
  23. * @returns {string | null} runtime code
  24. */
  25. generate() {
  26. const compilation = /** @type {Compilation} */ (this.compilation);
  27. const { runtimeTemplate } = compilation;
  28. // prefer a global `Worker` when present (web, Bun, polyfills), else `worker_threads.Worker`
  29. const nodeWorker = runtimeTemplate.getBuiltinModule(
  30. runtimeTemplate.renderNodePrefixForCoreModule("worker_threads"),
  31. ".Worker"
  32. );
  33. return `${RuntimeGlobals.worker} = typeof Worker !== "undefined" ? Worker : ${nodeWorker};`;
  34. }
  35. }
  36. module.exports = WorkerRuntimeModule;