FetchCompileWasmPlugin.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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("../Chunk")} Chunk */
  10. /** @typedef {import("../Compiler")} Compiler */
  11. // TODO webpack 6 remove
  12. const PLUGIN_NAME = "FetchCompileWasmPlugin";
  13. /**
  14. * @typedef {object} FetchCompileWasmPluginOptions
  15. * @property {boolean} [mangleImports] mangle imports
  16. */
  17. class FetchCompileWasmPlugin {
  18. /**
  19. * @param {FetchCompileWasmPluginOptions} [options] options
  20. */
  21. constructor(options = {}) {
  22. this.options = options;
  23. }
  24. /**
  25. * Apply the plugin
  26. * @param {Compiler} compiler the compiler instance
  27. * @returns {void}
  28. */
  29. apply(compiler) {
  30. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
  31. const globalWasmLoading = compilation.outputOptions.wasmLoading;
  32. /**
  33. * @param {Chunk} chunk chunk
  34. * @returns {boolean} true, if wasm loading is enabled for the chunk
  35. */
  36. const isEnabledForChunk = chunk => {
  37. const options = chunk.getEntryOptions();
  38. const wasmLoading =
  39. options && options.wasmLoading !== undefined
  40. ? options.wasmLoading
  41. : globalWasmLoading;
  42. return wasmLoading === "fetch";
  43. };
  44. /**
  45. * @param {string} path path to the wasm file
  46. * @returns {string} code to load the wasm file
  47. */
  48. const generateLoadBinaryCode = path =>
  49. `fetch(${RuntimeGlobals.publicPath} + ${path})`;
  50. compilation.hooks.runtimeRequirementInTree
  51. .for(RuntimeGlobals.ensureChunkHandlers)
  52. .tap(PLUGIN_NAME, (chunk, set) => {
  53. if (!isEnabledForChunk(chunk)) return;
  54. const chunkGraph = compilation.chunkGraph;
  55. if (
  56. !chunkGraph.hasModuleInGraph(
  57. chunk,
  58. m => m.type === WEBASSEMBLY_MODULE_TYPE_SYNC
  59. )
  60. ) {
  61. return;
  62. }
  63. set.add(RuntimeGlobals.moduleCache);
  64. set.add(RuntimeGlobals.publicPath);
  65. compilation.addRuntimeModule(
  66. chunk,
  67. new WasmChunkLoadingRuntimeModule({
  68. generateLoadBinaryCode,
  69. supportsStreaming: true,
  70. mangleImports: this.options.mangleImports,
  71. runtimeRequirements: set
  72. })
  73. );
  74. });
  75. });
  76. }
  77. }
  78. module.exports = FetchCompileWasmPlugin;