ConsumeSharedModule.js 7.8 KB

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