FetchCompileWasmPlugin.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 WasmChunkLoadingRuntimeModule = require("../wasm-sync/WasmChunkLoadingRuntimeModule");
  8. /** @typedef {import("../Compiler")} Compiler */
  9. // TODO webpack 6 remove
  10. class FetchCompileWasmPlugin {
  11. constructor(options) {
  12. this.options = options || {};
  13. }
  14. /**
  15. * Apply the plugin
  16. * @param {Compiler} compiler the compiler instance
  17. * @returns {void}
  18. */
  19. apply(compiler) {
  20. compiler.hooks.thisCompilation.tap(
  21. "FetchCompileWasmPlugin",
  22. compilation => {
  23. const globalWasmLoading = compilation.outputOptions.wasmLoading;
  24. const isEnabledForChunk = chunk => {
  25. const options = chunk.getEntryOptions();
  26. const wasmLoading =
  27. options && options.wasmLoading !== undefined
  28. ? options.wasmLoading
  29. : globalWasmLoading;
  30. return wasmLoading === "fetch";
  31. };
  32. const generateLoadBinaryCode = path =>
  33. `fetch(${RuntimeGlobals.publicPath} + ${path})`;
  34. compilation.hooks.runtimeRequirementInTree
  35. .for(RuntimeGlobals.ensureChunkHandlers)
  36. .tap("FetchCompileWasmPlugin", (chunk, set) => {
  37. if (!isEnabledForChunk(chunk)) return;
  38. const chunkGraph = compilation.chunkGraph;
  39. if (
  40. !chunkGraph.hasModuleInGraph(
  41. chunk,
  42. m => m.type === "webassembly/sync"
  43. )
  44. ) {
  45. return;
  46. }
  47. set.add(RuntimeGlobals.moduleCache);
  48. set.add(RuntimeGlobals.publicPath);
  49. compilation.addRuntimeModule(
  50. chunk,
  51. new WasmChunkLoadingRuntimeModule({
  52. generateLoadBinaryCode,
  53. supportsStreaming: true,
  54. mangleImports: this.options.mangleImports,
  55. runtimeRequirements: set
  56. })
  57. );
  58. });
  59. }
  60. );
  61. }
  62. }
  63. module.exports = FetchCompileWasmPlugin;