webpack/lib/runtime/EnsureChunkRuntimeModule.js

70 lines
2.2 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
2023-06-13 01:24:59 +08:00
/** @typedef {import("../Compilation")} Compilation */
2024-03-18 23:28:40 +08:00
/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
2023-06-13 01:24:59 +08:00
class EnsureChunkRuntimeModule extends RuntimeModule {
2023-05-25 03:37:58 +08:00
/**
2024-03-18 23:28:40 +08:00
* @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
2023-05-25 03:37:58 +08:00
*/
constructor(runtimeRequirements) {
super("ensure chunk");
this.runtimeRequirements = runtimeRequirements;
}
/**
2023-06-17 01:13:03 +08:00
* @returns {string | null} runtime code
*/
generate() {
2023-06-13 01:24:59 +08:00
const compilation = /** @type {Compilation} */ (this.compilation);
const { runtimeTemplate } = compilation;
// Check if there are non initial chunks which need to be imported using require-ensure
if (this.runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers)) {
const withFetchPriority = this.runtimeRequirements.has(
RuntimeGlobals.hasFetchPriority
);
const handlers = RuntimeGlobals.ensureChunkHandlers;
return Template.asString([
`${handlers} = {};`,
"// This file contains only the entry chunk.",
"// The chunk loading function for additional chunks",
2021-05-11 15:31:46 +08:00
`${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.basicFunction(
`chunkId${withFetchPriority ? ", fetchPriority" : ""}`,
2021-05-11 15:31:46 +08:00
[
`return Promise.all(Object.keys(${handlers}).reduce(${runtimeTemplate.basicFunction(
"promises, key",
[
`${handlers}[key](chunkId, promises${
2023-06-13 05:32:42 +08:00
withFetchPriority ? ", fetchPriority" : ""
});`,
"return promises;"
]
2021-05-11 15:31:46 +08:00
)}, []));`
]
)};`
]);
} else {
// There ensureChunk is used somewhere in the tree, so we need an empty requireEnsure
// function. This can happen with multiple entrypoints.
return Template.asString([
"// The chunk loading function for additional chunks",
"// Since all referenced chunks are already included",
"// in this file, this function is empty here.",
`${RuntimeGlobals.ensureChunk} = ${runtimeTemplate.returningFunction(
"Promise.resolve()"
)};`
]);
}
}
}
module.exports = EnsureChunkRuntimeModule;