diff --git a/lib/WebpackOptionsDefaulter.js b/lib/WebpackOptionsDefaulter.js index e709b402e..c3b9d08bf 100644 --- a/lib/WebpackOptionsDefaulter.js +++ b/lib/WebpackOptionsDefaulter.js @@ -161,6 +161,11 @@ class WebpackOptionsDefaulter extends OptionsDefaulter { this.set("output.hashDigestLength", 20); this.set("output.devtoolLineToLine", false); this.set("output.strictModuleExceptionHandling", false); + this.set("output.entryPrefetchFunction", "make", options => { + return Template.toIdentifier( + "webpackEntryPrefetch" + Template.toIdentifier(options.output.library) + ); + }); this.set("node", "call", value => { if (typeof value === "boolean") { diff --git a/lib/web/JsonpMainTemplatePlugin.js b/lib/web/JsonpMainTemplatePlugin.js index ae1b4b285..2513314be 100644 --- a/lib/web/JsonpMainTemplatePlugin.js +++ b/lib/web/JsonpMainTemplatePlugin.js @@ -114,7 +114,7 @@ class JsonpMainTemplatePlugin { }); }; - const linkPreload = mainTemplate => { + const linkPreload = () => { const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType; return Template.asString([ @@ -181,16 +181,19 @@ class JsonpMainTemplatePlugin { } if (needEntryChunkPrefetch(chunk)) { let preloadPrefetchChildren = chunk.getChildIdsByOrders(); + let entryPrefetchFunction = mainTemplate.outputOptions.entryPrefetchFunction; + let globalObject = mainTemplate.outputOptions.globalObject; + extraCode.push( "", "// preload or prefetch split chunks from entry chunk", - "(function prefetchOrPreloadFromEntry() {", + `${globalObject}['${entryPrefetchFunction}'] = () => {`, preloadPrefetchChildren.preload ? Template.indent([ `${JSON.stringify( preloadPrefetchChildren.preload )}.map(chunkId => {`, - Template.indent([linkPreload(mainTemplate)]), + Template.indent([linkPreload()]), `});` ]) : "", @@ -203,7 +206,7 @@ class JsonpMainTemplatePlugin { `});` ]) : "", - "})();" + "}", ); } if (extraCode.length === 0) return source; @@ -271,7 +274,7 @@ class JsonpMainTemplatePlugin { mainTemplate.hooks.linkPreload.tap( "JsonpMainTemplatePlugin", (_, chunk, hash) => { - return linkPreload(mainTemplate); + return linkPreload(); } ); mainTemplate.hooks.linkPrefetch.tap( diff --git a/test/configCases/web/prefetch-preload/index.js b/test/configCases/web/prefetch-preload/index.js index ee995727f..bd7aefc0b 100644 --- a/test/configCases/web/prefetch-preload/index.js +++ b/test/configCases/web/prefetch-preload/index.js @@ -21,7 +21,7 @@ it("should prefetch and preload child chunks on chunk load", (done) => { __webpack_nonce__ = "nonce"; __webpack_public_path__ = "/public/path/"; - const promise = import(/* webpackChunkName: "chunk1" */ "./chunk1"); + const promise = import(/* webpackChunkName: "chunk1", webpackPrefetch: true */ "./chunk1"); expect(document.head._children).toHaveLength(2); const script = document.head._children[0]; expect(script._type).toBe("script");