ReadFileCompileWasmPlugin.js 2.4 KB

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