FetchCompileAsyncWasmPlugin.js 1.6 KB

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