FetchCompileWasmPlugin.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. /**
  12. * @typedef {object} FetchCompileWasmPluginOptions
  13. * @property {boolean} [mangleImports] mangle imports
  14. */
  15. // TODO webpack 6 remove
  16. const PLUGIN_NAME = "FetchCompileWasmPlugin";
  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, { chunkGraph }) => {
  53. if (!isEnabledForChunk(chunk)) return;
  54. if (
  55. !chunkGraph.hasModuleInGraph(
  56. chunk,
  57. m => m.type === WEBASSEMBLY_MODULE_TYPE_SYNC
  58. )
  59. ) {
  60. return;
  61. }
  62. set.add(RuntimeGlobals.moduleCache);
  63. set.add(RuntimeGlobals.publicPath);
  64. compilation.addRuntimeModule(
  65. chunk,
  66. new WasmChunkLoadingRuntimeModule({
  67. generateLoadBinaryCode,
  68. supportsStreaming: true,
  69. mangleImports: this.options.mangleImports,
  70. runtimeRequirements: set
  71. })
  72. );
  73. });
  74. });
  75. }
  76. }
  77. module.exports = FetchCompileWasmPlugin;