UNPKG

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