ReadFileCompileWasmPlugin.js 3.9 KB

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