ConsumeSharedModule.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { RawSource } = require("webpack-sources");
  7. const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
  8. const Module = require("../Module");
  9. const {
  10. WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE
  11. } = require("../ModuleTypeConstants");
  12. const RuntimeGlobals = require("../RuntimeGlobals");
  13. const makeSerializable = require("../util/makeSerializable");
  14. const { rangeToString, stringifyHoley } = require("../util/semver");
  15. const ConsumeSharedFallbackDependency = require("./ConsumeSharedFallbackDependency");
  16. /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  17. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  18. /** @typedef {import("../ChunkGroup")} ChunkGroup */
  19. /** @typedef {import("../Compilation")} Compilation */
  20. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  21. /** @typedef {import("../Module").CodeGenerationContext} CodeGenerationContext */
  22. /** @typedef {import("../Module").CodeGenerationResult} CodeGenerationResult */
  23. /** @typedef {import("../Module").LibIdentOptions} LibIdentOptions */
  24. /** @typedef {import("../Module").NeedBuildContext} NeedBuildContext */
  25. /** @typedef {import("../RequestShortener")} RequestShortener */
  26. /** @typedef {import("../ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  27. /** @typedef {import("../WebpackError")} WebpackError */
  28. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  29. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  30. /** @typedef {import("../util/Hash")} Hash */
  31. /** @typedef {import("../util/fs").InputFileSystem} InputFileSystem */
  32. /** @typedef {import("../util/semver").SemVerRange} SemVerRange */
  33. /**
  34. * @typedef {Object} ConsumeOptions
  35. * @property {string=} import fallback request
  36. * @property {string=} importResolved resolved fallback request
  37. * @property {string} shareKey global share key
  38. * @property {string} shareScope share scope
  39. * @property {SemVerRange | false | undefined} requiredVersion version requirement
  40. * @property {string} packageName package name to determine required version automatically
  41. * @property {boolean} strictVersion don't use shared version even if version isn't valid
  42. * @property {boolean} singleton use single global version
  43. * @property {boolean} eager include the fallback module in a sync way
  44. */
  45. const TYPES = new Set(["consume-shared"]);
  46. class ConsumeSharedModule extends Module {
  47. /**
  48. * @param {string} context context
  49. * @param {ConsumeOptions} options consume options
  50. */
  51. constructor(context, options) {
  52. super(WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE, context);
  53. this.options = options;
  54. }
  55. /**
  56. * @returns {string} a unique identifier of the module
  57. */
  58. identifier() {
  59. const {
  60. shareKey,
  61. shareScope,
  62. importResolved,
  63. requiredVersion,
  64. strictVersion,
  65. singleton,
  66. eager
  67. } = this.options;
  68. return `${WEBPACK_MODULE_TYPE_CONSUME_SHARED_MODULE}|${shareScope}|${shareKey}|${
  69. requiredVersion && rangeToString(requiredVersion)
  70. }|${strictVersion}|${importResolved}|${singleton}|${eager}`;
  71. }
  72. /**
  73. * @param {RequestShortener} requestShortener the request shortener
  74. * @returns {string} a user readable identifier of the module
  75. */
  76. readableIdentifier(requestShortener) {
  77. const {
  78. shareKey,
  79. shareScope,
  80. importResolved,
  81. requiredVersion,
  82. strictVersion,
  83. singleton,
  84. eager
  85. } = this.options;
  86. return `consume shared module (${shareScope}) ${shareKey}@${
  87. requiredVersion ? rangeToString(requiredVersion) : "*"
  88. }${strictVersion ? " (strict)" : ""}${singleton ? " (singleton)" : ""}${
  89. importResolved
  90. ? ` (fallback: ${requestShortener.shorten(importResolved)})`
  91. : ""
  92. }${eager ? " (eager)" : ""}`;
  93. }
  94. /**
  95. * @param {LibIdentOptions} options options
  96. * @returns {string | null} an identifier for library inclusion
  97. */
  98. libIdent(options) {
  99. const { shareKey, shareScope, import: request } = this.options;
  100. return `${
  101. this.layer ? `(${this.layer})/` : ""
  102. }webpack/sharing/consume/${shareScope}/${shareKey}${
  103. request ? `/${request}` : ""
  104. }`;
  105. }
  106. /**
  107. * @param {NeedBuildContext} context context info
  108. * @param {function((WebpackError | null)=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
  109. * @returns {void}
  110. */
  111. needBuild(context, callback) {
  112. callback(null, !this.buildInfo);
  113. }
  114. /**
  115. * @param {WebpackOptions} options webpack options
  116. * @param {Compilation} compilation the compilation
  117. * @param {ResolverWithOptions} resolver the resolver
  118. * @param {InputFileSystem} fs the file system
  119. * @param {function(WebpackError=): void} callback callback function
  120. * @returns {void}
  121. */
  122. build(options, compilation, resolver, fs, callback) {
  123. this.buildMeta = {};
  124. this.buildInfo = {};
  125. if (this.options.import) {
  126. const dep = new ConsumeSharedFallbackDependency(this.options.import);
  127. if (this.options.eager) {
  128. this.addDependency(dep);
  129. } else {
  130. const block = new AsyncDependenciesBlock({});
  131. block.addDependency(dep);
  132. this.addBlock(block);
  133. }
  134. }
  135. callback();
  136. }
  137. /**
  138. * @returns {Set<string>} types available (do not mutate)
  139. */
  140. getSourceTypes() {
  141. return TYPES;
  142. }
  143. /**
  144. * @param {string=} type the source type for which the size should be estimated
  145. * @returns {number} the estimated size of the module (must be non-zero)
  146. */
  147. size(type) {
  148. return 42;
  149. }
  150. /**
  151. * @param {Hash} hash the hash used to track dependencies
  152. * @param {UpdateHashContext} context context
  153. * @returns {void}
  154. */
  155. updateHash(hash, context) {
  156. hash.update(JSON.stringify(this.options));
  157. super.updateHash(hash, context);
  158. }
  159. /**
  160. * @param {CodeGenerationContext} context context for code generation
  161. * @returns {CodeGenerationResult} result
  162. */
  163. codeGeneration({ chunkGraph, moduleGraph, runtimeTemplate }) {
  164. const runtimeRequirements = new Set([RuntimeGlobals.shareScopeMap]);
  165. const {
  166. shareScope,
  167. shareKey,
  168. strictVersion,
  169. requiredVersion,
  170. import: request,
  171. singleton,
  172. eager
  173. } = this.options;
  174. let fallbackCode;
  175. if (request) {
  176. if (eager) {
  177. const dep = this.dependencies[0];
  178. fallbackCode = runtimeTemplate.syncModuleFactory({
  179. dependency: dep,
  180. chunkGraph,
  181. runtimeRequirements,
  182. request: this.options.import
  183. });
  184. } else {
  185. const block = this.blocks[0];
  186. fallbackCode = runtimeTemplate.asyncModuleFactory({
  187. block,
  188. chunkGraph,
  189. runtimeRequirements,
  190. request: this.options.import
  191. });
  192. }
  193. }
  194. let fn = "load";
  195. const args = [JSON.stringify(shareScope), JSON.stringify(shareKey)];
  196. if (requiredVersion) {
  197. if (strictVersion) {
  198. fn += "Strict";
  199. }
  200. if (singleton) {
  201. fn += "Singleton";
  202. }
  203. args.push(stringifyHoley(requiredVersion));
  204. fn += "VersionCheck";
  205. } else {
  206. if (singleton) {
  207. fn += "Singleton";
  208. }
  209. }
  210. if (fallbackCode) {
  211. fn += "Fallback";
  212. args.push(fallbackCode);
  213. }
  214. const code = runtimeTemplate.returningFunction(`${fn}(${args.join(", ")})`);
  215. const sources = new Map();
  216. sources.set("consume-shared", new RawSource(code));
  217. return {
  218. runtimeRequirements,
  219. sources
  220. };
  221. }
  222. /**
  223. * @param {ObjectSerializerContext} context context
  224. */
  225. serialize(context) {
  226. const { write } = context;
  227. write(this.options);
  228. super.serialize(context);
  229. }
  230. /**
  231. * @param {ObjectDeserializerContext} context context
  232. */
  233. deserialize(context) {
  234. const { read } = context;
  235. this.options = read();
  236. super.deserialize(context);
  237. }
  238. }
  239. makeSerializable(
  240. ConsumeSharedModule,
  241. "webpack/lib/sharing/ConsumeSharedModule"
  242. );
  243. module.exports = ConsumeSharedModule;