2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
8 const RuntimeGlobals = require("../RuntimeGlobals");
9 const Template = require("../Template");
10 const AsyncWasmLoadingRuntimeModule = require("../wasm-async/AsyncWasmLoadingRuntimeModule");
12 /** @typedef {import("../Compiler")} Compiler */
14 class ReadFileCompileAsyncWasmPlugin {
15 constructor({ type = "async-node", import: useImport = false } = {}) {
17 this._import = useImport;
21 * @param {Compiler} compiler the compiler instance
25 compiler.hooks.thisCompilation.tap(
26 "ReadFileCompileAsyncWasmPlugin",
28 const globalWasmLoading = compilation.outputOptions.wasmLoading;
29 const isEnabledForChunk = chunk => {
30 const options = chunk.getEntryOptions();
32 options && options.wasmLoading !== undefined
35 return wasmLoading === this._type;
37 const generateLoadBinaryCode = this._import
40 "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {",
42 `readFile(new URL(${path}, import.meta.url), (err, buffer) => {`,
44 "if (err) return reject(err);",
46 "// Fake fetch response",
48 Template.indent(["arrayBuffer() { return buffer; }"]),
57 "new Promise(function (resolve, reject) {",
61 "var { readFile } = require('fs');",
62 "var { join } = require('path');",
64 `readFile(join(__dirname, ${path}), function(err, buffer){`,
66 "if (err) return reject(err);",
68 "// Fake fetch response",
70 Template.indent(["arrayBuffer() { return buffer; }"]),
75 "} catch (err) { reject(err); }"
80 compilation.hooks.runtimeRequirementInTree
81 .for(RuntimeGlobals.instantiateWasm)
82 .tap("ReadFileCompileAsyncWasmPlugin", (chunk, set) => {
83 if (!isEnabledForChunk(chunk)) return;
84 const chunkGraph = compilation.chunkGraph;
86 !chunkGraph.hasModuleInGraph(
88 m => m.type === "webassembly/async"
93 set.add(RuntimeGlobals.publicPath);
94 compilation.addRuntimeModule(
96 new AsyncWasmLoadingRuntimeModule({
97 generateLoadBinaryCode,
98 supportsStreaming: false
107 module.exports = ReadFileCompileAsyncWasmPlugin;