1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | */
|
---|
4 |
|
---|
5 | "use strict";
|
---|
6 |
|
---|
7 | const { SyncWaterfallHook } = require("tapable");
|
---|
8 | const Compilation = require("../Compilation");
|
---|
9 | const RuntimeGlobals = require("../RuntimeGlobals");
|
---|
10 | const RuntimeModule = require("../RuntimeModule");
|
---|
11 | const Template = require("../Template");
|
---|
12 | const {
|
---|
13 | getChunkFilenameTemplate,
|
---|
14 | chunkHasJs
|
---|
15 | } = require("../javascript/JavascriptModulesPlugin");
|
---|
16 | const { getInitialChunkIds } = require("../javascript/StartupHelpers");
|
---|
17 | const compileBooleanMatcher = require("../util/compileBooleanMatcher");
|
---|
18 | const { getUndoPath } = require("../util/identifier");
|
---|
19 |
|
---|
20 | /** @typedef {import("../../declarations/WebpackOptions").Environment} Environment */
|
---|
21 | /** @typedef {import("../Chunk")} Chunk */
|
---|
22 | /** @typedef {import("../ChunkGraph")} ChunkGraph */
|
---|
23 | /** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
|
---|
24 |
|
---|
25 | /**
|
---|
26 | * @typedef {object} JsonpCompilationPluginHooks
|
---|
27 | * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload
|
---|
28 | * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch
|
---|
29 | */
|
---|
30 |
|
---|
31 | /** @type {WeakMap<Compilation, JsonpCompilationPluginHooks>} */
|
---|
32 | const compilationHooksMap = new WeakMap();
|
---|
33 |
|
---|
34 | class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
|
---|
35 | /**
|
---|
36 | * @param {Compilation} compilation the compilation
|
---|
37 | * @returns {JsonpCompilationPluginHooks} hooks
|
---|
38 | */
|
---|
39 | static getCompilationHooks(compilation) {
|
---|
40 | if (!(compilation instanceof Compilation)) {
|
---|
41 | throw new TypeError(
|
---|
42 | "The 'compilation' argument must be an instance of Compilation"
|
---|
43 | );
|
---|
44 | }
|
---|
45 | let hooks = compilationHooksMap.get(compilation);
|
---|
46 | if (hooks === undefined) {
|
---|
47 | hooks = {
|
---|
48 | linkPreload: new SyncWaterfallHook(["source", "chunk"]),
|
---|
49 | linkPrefetch: new SyncWaterfallHook(["source", "chunk"])
|
---|
50 | };
|
---|
51 | compilationHooksMap.set(compilation, hooks);
|
---|
52 | }
|
---|
53 | return hooks;
|
---|
54 | }
|
---|
55 |
|
---|
56 | /**
|
---|
57 | * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
|
---|
58 | */
|
---|
59 | constructor(runtimeRequirements) {
|
---|
60 | super("import chunk loading", RuntimeModule.STAGE_ATTACH);
|
---|
61 | this._runtimeRequirements = runtimeRequirements;
|
---|
62 | }
|
---|
63 |
|
---|
64 | /**
|
---|
65 | * @private
|
---|
66 | * @param {Chunk} chunk chunk
|
---|
67 | * @param {string} rootOutputDir root output directory
|
---|
68 | * @returns {string} generated code
|
---|
69 | */
|
---|
70 | _generateBaseUri(chunk, rootOutputDir) {
|
---|
71 | const options = chunk.getEntryOptions();
|
---|
72 | if (options && options.baseUri) {
|
---|
73 | return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
|
---|
74 | }
|
---|
75 | const compilation = /** @type {Compilation} */ (this.compilation);
|
---|
76 | const {
|
---|
77 | outputOptions: { importMetaName }
|
---|
78 | } = compilation;
|
---|
79 | return `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify(
|
---|
80 | rootOutputDir
|
---|
81 | )}, ${importMetaName}.url);`;
|
---|
82 | }
|
---|
83 |
|
---|
84 | /**
|
---|
85 | * @returns {string | null} runtime code
|
---|
86 | */
|
---|
87 | generate() {
|
---|
88 | const compilation = /** @type {Compilation} */ (this.compilation);
|
---|
89 | const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
|
---|
90 | const chunk = /** @type {Chunk} */ (this.chunk);
|
---|
91 | const environment =
|
---|
92 | /** @type {Environment} */
|
---|
93 | (compilation.outputOptions.environment);
|
---|
94 | const {
|
---|
95 | runtimeTemplate,
|
---|
96 | outputOptions: { importFunctionName, crossOriginLoading }
|
---|
97 | } = compilation;
|
---|
98 | const fn = RuntimeGlobals.ensureChunkHandlers;
|
---|
99 | const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI);
|
---|
100 | const withExternalInstallChunk = this._runtimeRequirements.has(
|
---|
101 | RuntimeGlobals.externalInstallChunk
|
---|
102 | );
|
---|
103 | const withLoading = this._runtimeRequirements.has(
|
---|
104 | RuntimeGlobals.ensureChunkHandlers
|
---|
105 | );
|
---|
106 | const withOnChunkLoad = this._runtimeRequirements.has(
|
---|
107 | RuntimeGlobals.onChunksLoaded
|
---|
108 | );
|
---|
109 | const withHmr = this._runtimeRequirements.has(
|
---|
110 | RuntimeGlobals.hmrDownloadUpdateHandlers
|
---|
111 | );
|
---|
112 | const { linkPreload, linkPrefetch } =
|
---|
113 | ModuleChunkLoadingRuntimeModule.getCompilationHooks(compilation);
|
---|
114 | const isNeutralPlatform = runtimeTemplate.isNeutralPlatform();
|
---|
115 | const withPrefetch =
|
---|
116 | (environment.document || isNeutralPlatform) &&
|
---|
117 | this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) &&
|
---|
118 | chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasJs);
|
---|
119 | const withPreload =
|
---|
120 | (environment.document || isNeutralPlatform) &&
|
---|
121 | this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) &&
|
---|
122 | chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasJs);
|
---|
123 | const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
|
---|
124 | const hasJsMatcher = compileBooleanMatcher(conditionMap);
|
---|
125 | const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
|
---|
126 |
|
---|
127 | const outputName = compilation.getPath(
|
---|
128 | getChunkFilenameTemplate(chunk, compilation.outputOptions),
|
---|
129 | {
|
---|
130 | chunk,
|
---|
131 | contentHashType: "javascript"
|
---|
132 | }
|
---|
133 | );
|
---|
134 | const rootOutputDir = getUndoPath(
|
---|
135 | outputName,
|
---|
136 | /** @type {string} */ (compilation.outputOptions.path),
|
---|
137 | true
|
---|
138 | );
|
---|
139 |
|
---|
140 | const stateExpression = withHmr
|
---|
141 | ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module`
|
---|
142 | : undefined;
|
---|
143 |
|
---|
144 | return Template.asString([
|
---|
145 | withBaseURI
|
---|
146 | ? this._generateBaseUri(chunk, rootOutputDir)
|
---|
147 | : "// no baseURI",
|
---|
148 | "",
|
---|
149 | "// object to store loaded and loading chunks",
|
---|
150 | "// undefined = chunk not loaded, null = chunk preloaded/prefetched",
|
---|
151 | "// [resolve, Promise] = chunk loading, 0 = chunk loaded",
|
---|
152 | `var installedChunks = ${
|
---|
153 | stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
|
---|
154 | }{`,
|
---|
155 | Template.indent(
|
---|
156 | Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
|
---|
157 | ",\n"
|
---|
158 | )
|
---|
159 | ),
|
---|
160 | "};",
|
---|
161 | "",
|
---|
162 | withLoading || withExternalInstallChunk
|
---|
163 | ? `var installChunk = ${runtimeTemplate.basicFunction("data", [
|
---|
164 | runtimeTemplate.destructureObject(
|
---|
165 | ["__webpack_ids__", "__webpack_modules__", "__webpack_runtime__"],
|
---|
166 | "data"
|
---|
167 | ),
|
---|
168 | '// add "modules" to the modules object,',
|
---|
169 | '// then flag all "ids" as loaded and fire callback',
|
---|
170 | "var moduleId, chunkId, i = 0;",
|
---|
171 | "for(moduleId in __webpack_modules__) {",
|
---|
172 | Template.indent([
|
---|
173 | `if(${RuntimeGlobals.hasOwnProperty}(__webpack_modules__, moduleId)) {`,
|
---|
174 | Template.indent(
|
---|
175 | `${RuntimeGlobals.moduleFactories}[moduleId] = __webpack_modules__[moduleId];`
|
---|
176 | ),
|
---|
177 | "}"
|
---|
178 | ]),
|
---|
179 | "}",
|
---|
180 | `if(__webpack_runtime__) __webpack_runtime__(${RuntimeGlobals.require});`,
|
---|
181 | "for(;i < __webpack_ids__.length; i++) {",
|
---|
182 | Template.indent([
|
---|
183 | "chunkId = __webpack_ids__[i];",
|
---|
184 | `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
|
---|
185 | Template.indent("installedChunks[chunkId][0]();"),
|
---|
186 | "}",
|
---|
187 | "installedChunks[__webpack_ids__[i]] = 0;"
|
---|
188 | ]),
|
---|
189 | "}",
|
---|
190 | withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
|
---|
191 | ])}`
|
---|
192 | : "// no install chunk",
|
---|
193 | "",
|
---|
194 | withLoading
|
---|
195 | ? Template.asString([
|
---|
196 | `${fn}.j = ${runtimeTemplate.basicFunction(
|
---|
197 | "chunkId, promises",
|
---|
198 | hasJsMatcher !== false
|
---|
199 | ? Template.indent([
|
---|
200 | "// import() chunk loading for javascript",
|
---|
201 | `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
|
---|
202 | 'if(installedChunkData !== 0) { // 0 means "already installed".',
|
---|
203 | Template.indent([
|
---|
204 | "",
|
---|
205 | '// a Promise means "currently loading".',
|
---|
206 | "if(installedChunkData) {",
|
---|
207 | Template.indent([
|
---|
208 | "promises.push(installedChunkData[1]);"
|
---|
209 | ]),
|
---|
210 | "} else {",
|
---|
211 | Template.indent([
|
---|
212 | hasJsMatcher === true
|
---|
213 | ? "if(true) { // all chunks have JS"
|
---|
214 | : `if(${hasJsMatcher("chunkId")}) {`,
|
---|
215 | Template.indent([
|
---|
216 | "// setup Promise in chunk cache",
|
---|
217 | `var promise = ${importFunctionName}(${JSON.stringify(
|
---|
218 | rootOutputDir
|
---|
219 | )} + ${
|
---|
220 | RuntimeGlobals.getChunkScriptFilename
|
---|
221 | }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction(
|
---|
222 | "e",
|
---|
223 | [
|
---|
224 | "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;",
|
---|
225 | "throw e;"
|
---|
226 | ]
|
---|
227 | )});`,
|
---|
228 | `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction(
|
---|
229 | "installedChunkData = installedChunks[chunkId] = [resolve]",
|
---|
230 | "resolve"
|
---|
231 | )})])`,
|
---|
232 | "promises.push(installedChunkData[1] = promise);"
|
---|
233 | ]),
|
---|
234 | hasJsMatcher === true
|
---|
235 | ? "}"
|
---|
236 | : "} else installedChunks[chunkId] = 0;"
|
---|
237 | ]),
|
---|
238 | "}"
|
---|
239 | ]),
|
---|
240 | "}"
|
---|
241 | ])
|
---|
242 | : Template.indent(["installedChunks[chunkId] = 0;"])
|
---|
243 | )};`
|
---|
244 | ])
|
---|
245 | : "// no chunk on demand loading",
|
---|
246 | "",
|
---|
247 | withPrefetch && hasJsMatcher !== false
|
---|
248 | ? `${
|
---|
249 | RuntimeGlobals.prefetchChunkHandlers
|
---|
250 | }.j = ${runtimeTemplate.basicFunction("chunkId", [
|
---|
251 | `if((!${
|
---|
252 | RuntimeGlobals.hasOwnProperty
|
---|
253 | }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
|
---|
254 | hasJsMatcher === true ? "true" : hasJsMatcher("chunkId")
|
---|
255 | }) {`,
|
---|
256 | Template.indent([
|
---|
257 | "installedChunks[chunkId] = null;",
|
---|
258 | isNeutralPlatform
|
---|
259 | ? "if (typeof document === 'undefined') return;"
|
---|
260 | : "",
|
---|
261 | linkPrefetch.call(
|
---|
262 | Template.asString([
|
---|
263 | "var link = document.createElement('link');",
|
---|
264 | crossOriginLoading
|
---|
265 | ? `link.crossOrigin = ${JSON.stringify(
|
---|
266 | crossOriginLoading
|
---|
267 | )};`
|
---|
268 | : "",
|
---|
269 | `if (${RuntimeGlobals.scriptNonce}) {`,
|
---|
270 | Template.indent(
|
---|
271 | `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
|
---|
272 | ),
|
---|
273 | "}",
|
---|
274 | 'link.rel = "prefetch";',
|
---|
275 | 'link.as = "script";',
|
---|
276 | `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`
|
---|
277 | ]),
|
---|
278 | chunk
|
---|
279 | ),
|
---|
280 | "document.head.appendChild(link);"
|
---|
281 | ]),
|
---|
282 | "}"
|
---|
283 | ])};`
|
---|
284 | : "// no prefetching",
|
---|
285 | "",
|
---|
286 | withPreload && hasJsMatcher !== false
|
---|
287 | ? `${
|
---|
288 | RuntimeGlobals.preloadChunkHandlers
|
---|
289 | }.j = ${runtimeTemplate.basicFunction("chunkId", [
|
---|
290 | `if((!${
|
---|
291 | RuntimeGlobals.hasOwnProperty
|
---|
292 | }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
|
---|
293 | hasJsMatcher === true ? "true" : hasJsMatcher("chunkId")
|
---|
294 | }) {`,
|
---|
295 | Template.indent([
|
---|
296 | "installedChunks[chunkId] = null;",
|
---|
297 | isNeutralPlatform
|
---|
298 | ? "if (typeof document === 'undefined') return;"
|
---|
299 | : "",
|
---|
300 | linkPreload.call(
|
---|
301 | Template.asString([
|
---|
302 | "var link = document.createElement('link');",
|
---|
303 | "link.charset = 'utf-8';",
|
---|
304 | `if (${RuntimeGlobals.scriptNonce}) {`,
|
---|
305 | Template.indent(
|
---|
306 | `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
|
---|
307 | ),
|
---|
308 | "}",
|
---|
309 | 'link.rel = "modulepreload";',
|
---|
310 | `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
|
---|
311 | crossOriginLoading
|
---|
312 | ? crossOriginLoading === "use-credentials"
|
---|
313 | ? 'link.crossOrigin = "use-credentials";'
|
---|
314 | : Template.asString([
|
---|
315 | "if (link.href.indexOf(window.location.origin + '/') !== 0) {",
|
---|
316 | Template.indent(
|
---|
317 | `link.crossOrigin = ${JSON.stringify(
|
---|
318 | crossOriginLoading
|
---|
319 | )};`
|
---|
320 | ),
|
---|
321 | "}"
|
---|
322 | ])
|
---|
323 | : ""
|
---|
324 | ]),
|
---|
325 | chunk
|
---|
326 | ),
|
---|
327 | "document.head.appendChild(link);"
|
---|
328 | ]),
|
---|
329 | "}"
|
---|
330 | ])};`
|
---|
331 | : "// no preloaded",
|
---|
332 | "",
|
---|
333 | withExternalInstallChunk
|
---|
334 | ? Template.asString([
|
---|
335 | `${RuntimeGlobals.externalInstallChunk} = installChunk;`
|
---|
336 | ])
|
---|
337 | : "// no external install chunk",
|
---|
338 | "",
|
---|
339 | withOnChunkLoad
|
---|
340 | ? `${
|
---|
341 | RuntimeGlobals.onChunksLoaded
|
---|
342 | }.j = ${runtimeTemplate.returningFunction(
|
---|
343 | "installedChunks[chunkId] === 0",
|
---|
344 | "chunkId"
|
---|
345 | )};`
|
---|
346 | : "// no on chunks loaded"
|
---|
347 | ]);
|
---|
348 | }
|
---|
349 | }
|
---|
350 |
|
---|
351 | module.exports = ModuleChunkLoadingRuntimeModule;
|
---|