ReadFileCompileWasmTemplatePlugin.js
1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Template = require("../Template");
const WasmMainTemplatePlugin = require("../wasm/WasmMainTemplatePlugin");
class ReadFileCompileWasmTemplatePlugin {
constructor(options) {
this.options = options || {};
}
apply(compiler) {
compiler.hooks.thisCompilation.tap(
"ReadFileCompileWasmTemplatePlugin",
compilation => {
const generateLoadBinaryCode = path =>
Template.asString([
"new Promise(function (resolve, reject) {",
Template.indent([
"var { readFile } = require('fs');",
"var { join } = require('path');",
"",
"try {",
Template.indent([
`readFile(join(__dirname, ${path}), function(err, buffer){`,
Template.indent([
"if (err) return reject(err);",
"",
"// Fake fetch response",
"resolve({",
Template.indent([
"arrayBuffer() { return Promise.resolve(buffer); }"
]),
"});"
]),
"});"
]),
"} catch (err) { reject(err); }"
]),
"})"
]);
const plugin = new WasmMainTemplatePlugin(
Object.assign(
{
generateLoadBinaryCode,
supportsStreaming: false
},
this.options
)
);
plugin.apply(compilation.mainTemplate);
}
);
}
}
module.exports = ReadFileCompileWasmTemplatePlugin;