FetchCompileAsyncWasmPlugin.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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("../Chunk")} Chunk */
  10. /** @typedef {import("../Compiler")} Compiler */
  11. class FetchCompileAsyncWasmPlugin {
  12. /**
  13. * Apply the plugin
  14. * @param {Compiler} compiler the compiler instance
  15. * @returns {void}
  16. */
  17. apply(compiler) {
  18. compiler.hooks.thisCompilation.tap(
  19. "FetchCompileAsyncWasmPlugin",
  20. compilation => {
  21. const globalWasmLoading = compilation.outputOptions.wasmLoading;
  22. /**
  23. * @param {Chunk} chunk chunk
  24. * @returns {boolean} true, if wasm loading is enabled for the chunk
  25. */
  26. const isEnabledForChunk = chunk => {
  27. const options = chunk.getEntryOptions();
  28. const wasmLoading =
  29. options && options.wasmLoading !== undefined
  30. ? options.wasmLoading
  31. : globalWasmLoading;
  32. return wasmLoading === "fetch";
  33. };
  34. /**
  35. * @param {string} path path to the wasm file
  36. * @returns {string} code to load the wasm file
  37. */
  38. const generateLoadBinaryCode = path =>
  39. `fetch(${RuntimeGlobals.publicPath} + ${path})`;
  40. compilation.hooks.runtimeRequirementInTree
  41. .for(RuntimeGlobals.instantiateWasm)
  42. .tap("FetchCompileAsyncWasmPlugin", (chunk, set) => {
  43. if (!isEnabledForChunk(chunk)) return;
  44. const chunkGraph = compilation.chunkGraph;
  45. if (
  46. !chunkGraph.hasModuleInGraph(
  47. chunk,
  48. m => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC
  49. )
  50. ) {
  51. return;
  52. }
  53. set.add(RuntimeGlobals.publicPath);
  54. compilation.addRuntimeModule(
  55. chunk,
  56. new AsyncWasmLoadingRuntimeModule({
  57. generateLoadBinaryCode,
  58. supportsStreaming: true
  59. })
  60. );
  61. });
  62. }
  63. );
  64. }
  65. }
  66. module.exports = FetchCompileAsyncWasmPlugin;