FetchCompileWasmPlugin.js 1.9 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 { WEBASSEMBLY_MODULE_TYPE_SYNC } = require("../ModuleTypeConstants");
  7. const RuntimeGlobals = require("../RuntimeGlobals");
  8. const WasmChunkLoadingRuntimeModule = require("../wasm-sync/WasmChunkLoadingRuntimeModule");
  9. /** @typedef {import("../Compiler")} Compiler */
  10. // TODO webpack 6 remove
  11. const PLUGIN_NAME = "FetchCompileWasmPlugin";
  12. class FetchCompileWasmPlugin {
  13. constructor(options) {
  14. this.options = options || {};
  15. }
  16. /**
  17. * Apply the plugin
  18. * @param {Compiler} compiler the compiler instance
  19. * @returns {void}
  20. */
  21. apply(compiler) {
  22. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, 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(PLUGIN_NAME, (chunk, set) => {
  37. if (!isEnabledForChunk(chunk)) return;
  38. const chunkGraph = compilation.chunkGraph;
  39. if (
  40. !chunkGraph.hasModuleInGraph(
  41. chunk,
  42. m => m.type === WEBASSEMBLY_MODULE_TYPE_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. module.exports = FetchCompileWasmPlugin;