UNPKG

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