FallbackModule.js 5.8 KB

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