UNPKG

3.12 kBJavaScriptView Raw
1/**
2 * Created by zuozhuo on 2017/2/10.
3 */
4'use strict'
5
6
7function CustomJsonpMainTemplatePlugin() {
8}
9CustomJsonpMainTemplatePlugin.prototype.constructor = CustomJsonpMainTemplatePlugin;
10CustomJsonpMainTemplatePlugin.prototype.apply = function (mainTemplate) {
11
12 // console.log('----------------------------------------------------',mainTemplate._plugins['require-ensure'].toString())
13 var newRequireEnsureTpl = function (_, chunk, hash) {
14 var filename = this.outputOptions.filename || "bundle.js";
15 var chunkFilename = this.outputOptions.chunkFilename || "[id]." + filename;
16 return this.asString([
17 "var triggerCustomEvent = function (eventName,eventParams) {" ,
18 " var event;" ,
19 " if (window.CustomEvent) " ,
20 " { " ,
21 " event = new CustomEvent(eventName, {detail: eventParams}); " ,
22 " } else { " ,
23 " event = document.createEvent('CustomEvent'); " ,
24 " event.initCustomEvent(eventName, true, true, eventParams); " ,
25 " }" ,
26 " document.dispatchEvent(event); " ,
27 "};",
28
29 "// \"0\" is the signal for \"already loaded\"",
30
31 "if(installedChunks[chunkId] === 0)",
32 this.indent("return callback.call(null, " + this.requireFn + ");"),
33 "",
34 "// an array means \"currently loading\".",
35 "if(installedChunks[chunkId] !== undefined) {",
36 this.indent("installedChunks[chunkId].push(callback);"),
37 "} else {",
38 this.indent([
39 "// start chunk loading",
40 "installedChunks[chunkId] = [callback];",
41 "var head = document.getElementsByTagName('head')[0];",
42 this.applyPluginsWaterfall("jsonp-script", "", chunk, hash),
43 "script.onload=function(){ triggerCustomEvent('webpackChunkLoaded'); };",
44 "head.appendChild(script);",
45 "triggerCustomEvent('webpackChunkLoading');"
46 ]),
47 "}"
48 ]);
49 };
50
51 mainTemplate.plugin("require-ensure", newRequireEnsureTpl);
52 // mainTemplate._plugins['require-ensure'] = [newRequireEnsureTpl];
53 // console.log('=====================================', mainTemplate._plugins['require-ensure'].toString())
54
55};
56
57
58
59
60
61
62
63// WebpackOptionsApply -> JsonpTemplatePlugin -> JsonpMainTemplatePlugin -> "require-ensure"
64function ChunkLoadingEventPlugin() {
65}
66ChunkLoadingEventPlugin.prototype.constructor = ChunkLoadingEventPlugin;
67ChunkLoadingEventPlugin.prototype.apply = function (compiler) {
68 var compileTarget = compiler.options.target;
69 if (["web", "node-webkit", "electron-renderer"].indexOf(compileTarget) > -1) {
70 // TODO 这里可能有个bug,在编译index.html时,使用的是NodeMainTemplatePlugin的"require-ensure"也被改成下面这个了
71 compiler.plugin("compilation", function (compilation) {
72 compilation.mainTemplate.apply(new CustomJsonpMainTemplatePlugin());
73 });
74 }
75};
76
77
78module.exports = ChunkLoadingEventPlugin;
\No newline at end of file