webpack/lib/node/ReadFileCompileWasmPlugin.js

82 lines
2.0 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
"use strict";
const RuntimeGlobals = require("../RuntimeGlobals");
2018-04-28 15:57:21 +08:00
const Template = require("../Template");
2019-05-22 14:59:26 +08:00
const WasmChunkLoadingRuntimeModule = require("../wasm/WasmChunkLoadingRuntimeModule");
2018-11-09 05:59:19 +08:00
/** @typedef {import("../Compiler")} Compiler */
class ReadFileCompileWasmPlugin {
constructor(options) {
this.options = options || {};
}
2018-11-09 05:59:19 +08:00
/**
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
2018-02-25 09:00:20 +08:00
compiler.hooks.thisCompilation.tap(
"ReadFileCompileWasmPlugin",
2018-02-25 09:00:20 +08:00
compilation => {
2018-04-28 15:57:21 +08:00
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); }"
]),
"})"
]);
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.ensureChunkHandlers)
.tap("ReadFileCompileWasmPlugin", (chunk, set) => {
const chunkGraph = compilation.chunkGraph;
if (
!chunkGraph.hasModuleInGraph(
chunk,
m => m.type === "webassembly/sync"
)
) {
return;
}
set.add(RuntimeGlobals.moduleCache);
compilation.addRuntimeModule(
chunk,
new WasmChunkLoadingRuntimeModule({
generateLoadBinaryCode,
supportsStreaming: false,
mangleImports: this.options.mangleImports
})
);
});
2018-02-25 09:00:20 +08:00
}
);
}
}
module.exports = ReadFileCompileWasmPlugin;