[79a0317] | 1 | /*
|
---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
| 3 | Author Tobias Koppers @sokra
|
---|
| 4 | */
|
---|
| 5 |
|
---|
| 6 | "use strict";
|
---|
| 7 |
|
---|
| 8 | const { WEBASSEMBLY_MODULE_TYPE_ASYNC } = require("../ModuleTypeConstants");
|
---|
| 9 | const RuntimeGlobals = require("../RuntimeGlobals");
|
---|
| 10 | const AsyncWasmLoadingRuntimeModule = require("../wasm-async/AsyncWasmLoadingRuntimeModule");
|
---|
| 11 |
|
---|
| 12 | /** @typedef {import("../Chunk")} Chunk */
|
---|
| 13 | /** @typedef {import("../Compiler")} Compiler */
|
---|
| 14 |
|
---|
| 15 | const PLUGIN_NAME = "FetchCompileAsyncWasmPlugin";
|
---|
| 16 |
|
---|
| 17 | class FetchCompileAsyncWasmPlugin {
|
---|
| 18 | /**
|
---|
| 19 | * Apply the plugin
|
---|
| 20 | * @param {Compiler} compiler the compiler instance
|
---|
| 21 | * @returns {void}
|
---|
| 22 | */
|
---|
| 23 | apply(compiler) {
|
---|
| 24 | compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
|
---|
| 25 | const globalWasmLoading = compilation.outputOptions.wasmLoading;
|
---|
| 26 | /**
|
---|
| 27 | * @param {Chunk} chunk chunk
|
---|
| 28 | * @returns {boolean} true, if wasm loading is enabled for the chunk
|
---|
| 29 | */
|
---|
| 30 | const isEnabledForChunk = chunk => {
|
---|
| 31 | const options = chunk.getEntryOptions();
|
---|
| 32 | const wasmLoading =
|
---|
| 33 | options && options.wasmLoading !== undefined
|
---|
| 34 | ? options.wasmLoading
|
---|
| 35 | : globalWasmLoading;
|
---|
| 36 | return wasmLoading === "fetch";
|
---|
| 37 | };
|
---|
| 38 | /**
|
---|
| 39 | * @param {string} path path to the wasm file
|
---|
| 40 | * @returns {string} code to load the wasm file
|
---|
| 41 | */
|
---|
| 42 | const generateLoadBinaryCode = path =>
|
---|
| 43 | `fetch(${RuntimeGlobals.publicPath} + ${path})`;
|
---|
| 44 |
|
---|
| 45 | compilation.hooks.runtimeRequirementInTree
|
---|
| 46 | .for(RuntimeGlobals.instantiateWasm)
|
---|
| 47 | .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => {
|
---|
| 48 | if (!isEnabledForChunk(chunk)) return;
|
---|
| 49 | if (
|
---|
| 50 | !chunkGraph.hasModuleInGraph(
|
---|
| 51 | chunk,
|
---|
| 52 | m => m.type === WEBASSEMBLY_MODULE_TYPE_ASYNC
|
---|
| 53 | )
|
---|
| 54 | ) {
|
---|
| 55 | return;
|
---|
| 56 | }
|
---|
| 57 | set.add(RuntimeGlobals.publicPath);
|
---|
| 58 | compilation.addRuntimeModule(
|
---|
| 59 | chunk,
|
---|
| 60 | new AsyncWasmLoadingRuntimeModule({
|
---|
| 61 | generateLoadBinaryCode,
|
---|
| 62 | supportsStreaming: true
|
---|
| 63 | })
|
---|
| 64 | );
|
---|
| 65 | });
|
---|
| 66 | });
|
---|
| 67 | }
|
---|
| 68 | }
|
---|
| 69 |
|
---|
| 70 | module.exports = FetchCompileAsyncWasmPlugin;
|
---|