ReadFileCompileWasmPlugin.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 Template = require("../Template");
  9. const WasmChunkLoadingRuntimeModule = require("../wasm-sync/WasmChunkLoadingRuntimeModule");
  10. /** @typedef {import("../Compiler")} Compiler */
  11. // TODO webpack 6 remove
  12. class ReadFileCompileWasmPlugin {
  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(
  23. "ReadFileCompileWasmPlugin",
  24. compilation => {
  25. const globalWasmLoading = compilation.outputOptions.wasmLoading;
  26. const isEnabledForChunk = chunk => {
  27. const options = chunk.getEntryOptions();
  28. const wasmLoading =
  29. options && options.wasmLoading !== undefined
  30. ? options.wasmLoading
  31. : globalWasmLoading;
  32. return wasmLoading === "async-node";
  33. };
  34. const generateLoadBinaryCode = path =>
  35. Template.asString([
  36. "new Promise(function (resolve, reject) {",
  37. Template.indent([
  38. "var { readFile } = require('fs');",
  39. "var { join } = require('path');",
  40. "",
  41. "try {",
  42. Template.indent([
  43. `readFile(join(__dirname, ${path}), function(err, buffer){`,
  44. Template.indent([
  45. "if (err) return reject(err);",
  46. "",
  47. "// Fake fetch response",
  48. "resolve({",
  49. Template.indent(["arrayBuffer() { return buffer; }"]),
  50. "});"
  51. ]),
  52. "});"
  53. ]),
  54. "} catch (err) { reject(err); }"
  55. ]),
  56. "})"
  57. ]);
  58. compilation.hooks.runtimeRequirementInTree
  59. .for(RuntimeGlobals.ensureChunkHandlers)
  60. .tap("ReadFileCompileWasmPlugin", (chunk, set) => {
  61. if (!isEnabledForChunk(chunk)) return;
  62. const chunkGraph = compilation.chunkGraph;
  63. if (
  64. !chunkGraph.hasModuleInGraph(
  65. chunk,
  66. m => m.type === WEBASSEMBLY_MODULE_TYPE_SYNC
  67. )
  68. ) {
  69. return;
  70. }
  71. set.add(RuntimeGlobals.moduleCache);
  72. compilation.addRuntimeModule(
  73. chunk,
  74. new WasmChunkLoadingRuntimeModule({
  75. generateLoadBinaryCode,
  76. supportsStreaming: false,
  77. mangleImports: this.options.mangleImports,
  78. runtimeRequirements: set
  79. })
  80. );
  81. });
  82. }
  83. );
  84. }
  85. }
  86. module.exports = ReadFileCompileWasmPlugin;