FallbackModule.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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 { JS_TYPES } = require("../ModuleSourceTypesConstants");
  9. const { WEBPACK_MODULE_TYPE_FALLBACK } = require("../ModuleTypeConstants");
  10. const RuntimeGlobals = require("../RuntimeGlobals");
  11. const Template = require("../Template");
  12. const makeSerializable = require("../util/makeSerializable");
  13. const FallbackItemDependency = require("./FallbackItemDependency");
  14. /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  15. /** @typedef {import("../Chunk")} Chunk */
  16. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  17. /** @typedef {import("../ChunkGroup")} ChunkGroup */
  18. /** @typedef {import("../Compilation")} Compilation */
  19. /** @typedef {import("../Module").BuildCallback} BuildCallback */
  20. /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
  21. /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
  22. /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
  23. /** @typedef {import("../Module").NeedBuildCallback} NeedBuildCallback */
  24. /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
  25. /** @typedef {import("../Module").SourceTypes} SourceTypes */
  26. /** @typedef {import("../RequestShortener")} RequestShortener */
  27. /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  28. /** @typedef {import("../WebpackError")} WebpackError */
  29. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  30. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  31. /** @typedef {import("../util/Hash")} Hash */
  32. /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
  33. const RUNTIME_REQUIREMENTS = new Set([RuntimeGlobals.module]);
  34. class FallbackModule extends Module {
  35. /**
  36. * @param {string[]} requests list of requests to choose one
  37. */
  38. constructor(requests) {
  39. super(WEBPACK_MODULE_TYPE_FALLBACK);
  40. this.requests = requests;
  41. this._identifier = `fallback ${this.requests.join(" ")}`;
  42. }
  43. /**
  44. * @returns {string} a unique identifier of the module
  45. */
  46. identifier() {
  47. return this._identifier;
  48. }
  49. /**
  50. * @param {RequestShortener} requestShortener the request shortener
  51. * @returns {string} a user readable identifier of the module
  52. */
  53. readableIdentifier(requestShortener) {
  54. return this._identifier;
  55. }
  56. /**
  57. * @param {LibIdentOptions} options options
  58. * @returns {string | null} an identifier for library inclusion
  59. */
  60. libIdent(options) {
  61. return `${this.layer ? `(${this.layer})/` : ""}webpack/container/fallback/${
  62. this.requests[0]
  63. }/and ${this.requests.length - 1} more`;
  64. }
  65. /**
  66. * @param {Chunk} chunk the chunk which condition should be checked
  67. * @param {Compilation} compilation the compilation
  68. * @returns {boolean} true, if the chunk is ok for the module
  69. */
  70. chunkCondition(chunk, { chunkGraph }) {
  71. return chunkGraph.getNumberOfEntryModules(chunk) > 0;
  72. }
  73. /**
  74. * @param {NeedBuildContext} context context info
  75. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  76. * @returns {void}
  77. */
  78. needBuild(context, callback) {
  79. callback(null, !this.buildInfo);
  80. }
  81. /**
  82. * @param {WebpackOptions} options webpack options
  83. * @param {Compilation} compilation the compilation
  84. * @param {ResolverWithOptions} resolver the resolver
  85. * @param {InputFileSystem} fs the file system
  86. * @param {BuildCallback} callback callback function
  87. * @returns {void}
  88. */
  89. build(options, compilation, resolver, fs, callback) {
  90. this.buildMeta = {};
  91. this.buildInfo = {
  92. strict: true
  93. };
  94. this.clearDependenciesAndBlocks();
  95. for (const request of this.requests) {
  96. this.addDependency(new FallbackItemDependency(request));
  97. }
  98. callback();
  99. }
  100. /**
  101. * @param {string=} type the source type for which the size should be estimated
  102. * @returns {number} the estimated size of the module (must be non-zero)
  103. */
  104. size(type) {
  105. return this.requests.length * 5 + 42;
  106. }
  107. /**
  108. * @returns {SourceTypes} types available (do not mutate)
  109. */
  110. getSourceTypes() {
  111. return JS_TYPES;
  112. }
  113. /**
  114. * @param {CodeGenerationContext} context context for code generation
  115. * @returns {CodeGenerationResult} result
  116. */
  117. codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
  118. const ids = this.dependencies.map(dep =>
  119. chunkGraph.getModuleId(/** @type {Module} */ (moduleGraph.getModule(dep)))
  120. );
  121. const code = Template.asString([
  122. `var ids = ${JSON.stringify(ids)};`,
  123. "var error, result, i = 0;",
  124. `var loop = ${runtimeTemplate.basicFunction("next", [
  125. "while(i < ids.length) {",
  126. Template.indent([
  127. `try { next = ${RuntimeGlobals.require}(ids[i++]); } catch(e) { return handleError(e); }`,
  128. "if(next) return next.then ? next.then(handleResult, handleError) : handleResult(next);"
  129. ]),
  130. "}",
  131. "if(error) throw error;"
  132. ])}`,
  133. `var handleResult = ${runtimeTemplate.basicFunction("result", [
  134. "if(result) return result;",
  135. "return loop();"
  136. ])};`,
  137. `var handleError = ${runtimeTemplate.basicFunction("e", [
  138. "error = e;",
  139. "return loop();"
  140. ])};`,
  141. "module.exports = loop();"
  142. ]);
  143. const sources = new Map();
  144. sources.set("javascript", new RawSource(code));
  145. return { sources, runtimeRequirements: RUNTIME_REQUIREMENTS };
  146. }
  147. /**
  148. * @param {ObjectSerializerContext} context context
  149. */
  150. serialize(context) {
  151. const { write } = context;
  152. write(this.requests);
  153. super.serialize(context);
  154. }
  155. /**
  156. * @param {ObjectDeserializerContext} context context
  157. * @returns {FallbackModule} deserialized fallback module
  158. */
  159. static deserialize(context) {
  160. const { read } = context;
  161. const obj = new FallbackModule(read());
  162. obj.deserialize(context);
  163. return obj;
  164. }
  165. }
  166. makeSerializable(FallbackModule, "webpack/lib/container/FallbackModule");
  167. module.exports = FallbackModule;