FetchCompileAsyncWasmPlugin.js 1.9 KB

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