ReadFileCompileWasmPlugin.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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("../Chunk")} Chunk */
  11. /** @typedef {import("../Compiler")} Compiler */
  12. /**
  13. * @typedef {object} ReadFileCompileWasmPluginOptions
  14. * @property {boolean} [mangleImports] mangle imports
  15. * @property {boolean} [import] use import?
  16. */
  17. // TODO webpack 6 remove
  18. const PLUGIN_NAME = "ReadFileCompileWasmPlugin";
  19. class ReadFileCompileWasmPlugin {
  20. /**
  21. * @param {ReadFileCompileWasmPluginOptions} [options] options object
  22. */
  23. constructor(options = {}) {
  24. this.options = options;
  25. }
  26. /**
  27. * Apply the plugin
  28. * @param {Compiler} compiler the compiler instance
  29. * @returns {void}
  30. */
  31. apply(compiler) {
  32. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
  33. const globalWasmLoading = compilation.outputOptions.wasmLoading;
  34. /**
  35. * @param {Chunk} chunk chunk
  36. * @returns {boolean} true, when wasm loading is enabled for the chunk
  37. */
  38. const isEnabledForChunk = chunk => {
  39. const options = chunk.getEntryOptions();
  40. const wasmLoading =
  41. options && options.wasmLoading !== undefined
  42. ? options.wasmLoading
  43. : globalWasmLoading;
  44. return wasmLoading === "async-node";
  45. };
  46. /**
  47. * @param {string} path path to wasm file
  48. * @returns {string} generated code to load the wasm file
  49. */
  50. const generateLoadBinaryCode = this.options.import
  51. ? path =>
  52. Template.asString([
  53. "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {",
  54. Template.indent([
  55. `readFile(new URL(${path}, ${compilation.outputOptions.importMetaName}.url), (err, buffer) => {`,
  56. Template.indent([
  57. "if (err) return reject(err);",
  58. "",
  59. "// Fake fetch response",
  60. "resolve({",
  61. Template.indent(["arrayBuffer() { return buffer; }"]),
  62. "});"
  63. ]),
  64. "});"
  65. ]),
  66. "}))"
  67. ])
  68. : path =>
  69. Template.asString([
  70. "new Promise(function (resolve, reject) {",
  71. Template.indent([
  72. "var { readFile } = require('fs');",
  73. "var { join } = require('path');",
  74. "",
  75. "try {",
  76. Template.indent([
  77. `readFile(join(__dirname, ${path}), function(err, buffer){`,
  78. Template.indent([
  79. "if (err) return reject(err);",
  80. "",
  81. "// Fake fetch response",
  82. "resolve({",
  83. Template.indent(["arrayBuffer() { return buffer; }"]),
  84. "});"
  85. ]),
  86. "});"
  87. ]),
  88. "} catch (err) { reject(err); }"
  89. ]),
  90. "})"
  91. ]);
  92. compilation.hooks.runtimeRequirementInTree
  93. .for(RuntimeGlobals.ensureChunkHandlers)
  94. .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => {
  95. if (!isEnabledForChunk(chunk)) return;
  96. if (
  97. !chunkGraph.hasModuleInGraph(
  98. chunk,
  99. m => m.type === WEBASSEMBLY_MODULE_TYPE_SYNC
  100. )
  101. ) {
  102. return;
  103. }
  104. set.add(RuntimeGlobals.moduleCache);
  105. compilation.addRuntimeModule(
  106. chunk,
  107. new WasmChunkLoadingRuntimeModule({
  108. generateLoadBinaryCode,
  109. supportsStreaming: false,
  110. mangleImports: this.options.mangleImports,
  111. runtimeRequirements: set
  112. })
  113. );
  114. });
  115. });
  116. }
  117. }
  118. module.exports = ReadFileCompileWasmPlugin;