FetchCompileAsyncWasmPlugin.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { WEBASSEMBLY_MODULE_TYPE_ASYNC } = require("../ModuleTypeConstants");
  7. const RuntimeGlobals = require("../RuntimeGlobals");
  8. const AsyncWasmLoadingRuntimeModule = require("../wasm-async/AsyncWasmLoadingRuntimeModule");
  9. /** @typedef {import("../Compiler")} Compiler */
  10. class FetchCompileAsyncWasmPlugin {
  11. /**
  12. * Apply the plugin
  13. * @param {Compiler} compiler the compiler instance
  14. * @returns {void}
  15. */
  16. apply(compiler) {
  17. compiler.hooks.thisCompilation.tap(
  18. "FetchCompileAsyncWasmPlugin",
  19. compilation => {
  20. const globalWasmLoading = compilation.outputOptions.wasmLoading;
  21. const isEnabledForChunk = chunk => {
  22. const options = chunk.getEntryOptions();
  23. const wasmLoading =
  24. options && options.wasmLoading !== undefined
  25. ? options.wasmLoading
  26. : globalWasmLoading;
  27. return wasmLoading === "fetch";
  28. };
  29. const generateLoadBinaryCode = path =>
  30. `fetch(${RuntimeGlobals.publicPath} + ${path})`;
  31. compilation.hooks.runtimeRequirementInTree
  32. .for(RuntimeGlobals.instantiateWasm)
  33. .tap("FetchCompileAsyncWasmPlugin", (chunk, set) => {
  34. if (!isEnabledForChunk(chunk)) return;
  35. const chunkGraph = compilation.chunkGraph;
  36. if (
  37. !chunkGraph.hasModuleInGraph(
  38. chunk,
  39. m => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC
  40. )
  41. ) {
  42. return;
  43. }
  44. set.add(RuntimeGlobals.publicPath);
  45. compilation.addRuntimeModule(
  46. chunk,
  47. new AsyncWasmLoadingRuntimeModule({
  48. generateLoadBinaryCode,
  49. supportsStreaming: true
  50. })
  51. );
  52. });
  53. }
  54. );
  55. }
  56. }
  57. module.exports = FetchCompileAsyncWasmPlugin;