FallbackModule.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy
  4. */
  5. "use strict";
  6. const { RawSource } = require("webpack-sources");
  7. const Module = require("../Module");
  8. const {
  9. JAVASCRIPT_TYPE,
  10. JAVASCRIPT_TYPES
  11. } = require("../ModuleSourceTypeConstants");
  12. const { WEBPACK_MODULE_TYPE_FALLBACK } = require("../ModuleTypeConstants");
  13. const RuntimeGlobals = require("../RuntimeGlobals");
  14. const Template = require("../Template");
  15. const makeSerializable = require("../util/makeSerializable");
  16. const FallbackItemDependency = require("./FallbackItemDependency");
  17. /**
  18. * @import {
  19. * WebpackOptionsNormalizedWithDefaults as WebpackOptions
  20. * } from "../config/defaults"
  21. */
  22. /** @import Chunk from "../Chunk" */
  23. /** @import Compilation from "../Compilation" */
  24. /**
  25. * @import {
  26. * BuildCallback,
  27. * CodeGenerationContext,
  28. * CodeGenerationResult,
  29. * LibIdentOptions,
  30. * LibIdent,
  31. * NeedBuildCallback,
  32. * NeedBuildContext,
  33. * Sources,
  34. * SourceTypes
  35. * } from "../Module"
  36. */
  37. /** @import RequestShortener from "../RequestShortener" */
  38. /** @import { ResolverWithOptions } from "../ResolverFactory" */
  39. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext<[ExternalRequests]>} ObjectDeserializerContext */
  40. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext<[ExternalRequests]>} ObjectSerializerContext */
  41. /** @import { InputFileSystem } from "../util/fs" */
  42. /** @import { ExternalRequests } from "./RemoteModule" */
  43. const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);
  44. class FallbackModule extends Module {
  45. /**
  46. * Creates an instance of FallbackModule.
  47. * @param {ExternalRequests} requests list of requests to choose one
  48. */
  49. constructor(requests) {
  50. super(WEBPACK_MODULE_TYPE_FALLBACK);
  51. /** @type {ExternalRequests} */
  52. this.requests = requests;
  53. /** @type {string} */
  54. this._identifier = `fallback ${this.requests.join(" ")}`;
  55. }
  56. /**
  57. * Returns the unique identifier used to reference this module.
  58. * @returns {string} a unique identifier of the module
  59. */
  60. identifier() {
  61. return this._identifier;
  62. }
  63. /**
  64. * Returns a human-readable identifier for this module.
  65. * @param {RequestShortener} requestShortener the request shortener
  66. * @returns {string} a user readable identifier of the module
  67. */
  68. readableIdentifier(requestShortener) {
  69. return this._identifier;
  70. }
  71. /**
  72. * Gets the library identifier.
  73. * @param {LibIdentOptions} options options
  74. * @returns {LibIdent | null} an identifier for library inclusion
  75. */
  76. libIdent(options) {
  77. return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${
  78. this.requests[0]
  79. }/and ${this.requests.length - 1} more`;
  80. }
  81. /**
  82. * Returns true if the module can be placed in the chunk.
  83. * @param {Chunk} chunk the chunk which condition should be checked
  84. * @param {Compilation} compilation the compilation
  85. * @returns {boolean} true if the module can be placed in the chunk
  86. */
  87. chunkCondition(chunk, { chunkGraph }) {
  88. return chunkGraph.getNumberOfEntryModules(chunk) > 0;
  89. }
  90. /**
  91. * Checks whether the module needs to be rebuilt for the current build state.
  92. * @param {NeedBuildContext} context context info
  93. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  94. * @returns {void}
  95. */
  96. needBuild(context, callback) {
  97. callback(null, !this.buildInfo);
  98. }
  99. /**
  100. * Builds the module using the provided compilation context.
  101. * @param {WebpackOptions} options webpack options
  102. * @param {Compilation} compilation the compilation
  103. * @param {ResolverWithOptions} resolver the resolver
  104. * @param {InputFileSystem} fs the file system
  105. * @param {BuildCallback} callback callback function
  106. * @returns {void}
  107. */
  108. build(options, compilation, resolver, fs, callback) {
  109. this.buildMeta = {};
  110. this.buildInfo = {
  111. strict: true
  112. };
  113. this.clearDependenciesAndBlocks();
  114. for (const request of this.requests) {
  115. this.addDependency(new FallbackItemDependency(request));
  116. }
  117. callback();
  118. }
  119. /**
  120. * Returns the estimated size for the requested source type.
  121. * @param {string=} type the source type for which the size should be estimated
  122. * @returns {number} the estimated size of the module (must be non-zero)
  123. */
  124. size(type) {
  125. return this.requests.length * 5 + 42;
  126. }
  127. /**
  128. * Returns the source types this module can generate.
  129. * @returns {SourceTypes} types available (do not mutate)
  130. */
  131. getSourceTypes() {
  132. return JAVASCRIPT_TYPES;
  133. }
  134. /**
  135. * Generates code and runtime requirements for this module.
  136. * @param {CodeGenerationContext} context context for code generation
  137. * @returns {CodeGenerationResult} result
  138. */
  139. codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
  140. const ids = this.dependencies.map((dep) =>
  141. chunkGraph.getModuleId(/** @type {Module} */ (moduleGraph.getModule(dep)))
  142. );
  143. const cst = runtimeTemplate.renderConst();
  144. const lt = runtimeTemplate.renderLet();
  145. const code = Template.asString([
  146. `${cst} ids = ${JSON.stringify(ids)};`,
  147. `${lt} error, result, i = 0;`,
  148. `${cst} loop = ${runtimeTemplate.basicFunction("next", [
  149. "while(i < ids.length) {",
  150. Template.indent([
  151. `try { next = ${RuntimeGlobals.require}(ids[i++]); } catch(e) { return handleError(e); }`,
  152. "if(next) return next.then ? next.then(handleResult, handleError) : handleResult(next);"
  153. ]),
  154. "}",
  155. "if(error) throw error;"
  156. ])}`,
  157. `${cst} handleResult = ${runtimeTemplate.basicFunction("result", [
  158. "if(result) return result;",
  159. "return loop();"
  160. ])};`,
  161. `${cst} handleError = ${runtimeTemplate.basicFunction("e", [
  162. "error = e;",
  163. "return loop();"
  164. ])};`,
  165. "module.exports = loop();"
  166. ]);
  167. /** @type {Sources} */
  168. const sources = new Map();
  169. sources.set(JAVASCRIPT_TYPE, new RawSource(code));
  170. return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS };
  171. }
  172. /**
  173. * Serializes this instance into the provided serializer context.
  174. * @param {ObjectSerializerContext} context context
  175. */
  176. serialize(context) {
  177. context.write(this.requests);
  178. super.serialize(context);
  179. }
  180. /**
  181. * Restores this instance from the provided deserializer context.
  182. * @param {ObjectDeserializerContext} context context
  183. * @returns {FallbackModule} deserialized fallback module
  184. */
  185. static deserialize(context) {
  186. const { read } = context;
  187. const obj = new FallbackModule(read());
  188. obj.deserialize(context);
  189. return obj;
  190. }
  191. }
  192. makeSerializable(FallbackModule, "webpack/lib/container/FallbackModule");
  193. module.exports = FallbackModule;