ConsumeSharedModule.js 7.1 KB

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