Skip to content

Commit 9ab1304

Browse files
authored
Merge pull request webpack#4343 from sendilkumarn/refactor-es6
Refactor NodestuffPlugin / JsonpMainTemplatePlugin / ModuleFilenameHelpers
2 parents e7c13d7 + 72f7176 commit 9ab1304

3 files changed

Lines changed: 283 additions & 287 deletions

File tree

‎lib/JsonpMainTemplatePlugin.js‎

Lines changed: 177 additions & 182 deletions
Original file line numberDiff line numberDiff line change
@@ -2,207 +2,202 @@
22
MIT License http://www.opensource.org/licenses/mit-license.php
33
Author Tobias Koppers @sokra
44
*/
5-
var Template = require("./Template");
5+
"use strict";
66

7-
function JsonpMainTemplatePlugin() {}
8-
module.exports = JsonpMainTemplatePlugin;
7+
const Template = require("./Template");
98

10-
JsonpMainTemplatePlugin.prototype.constructor = JsonpMainTemplatePlugin;
11-
JsonpMainTemplatePlugin.prototype.apply = function(mainTemplate) {
12-
mainTemplate.plugin("local-vars", function(source, chunk) {
13-
if(chunk.chunks.length > 0) {
14-
return this.asString([
15-
source,
16-
"",
17-
"// objects to store loaded and loading chunks",
18-
"var installedChunks = {",
19-
this.indent(
20-
chunk.ids.map(function(id) {
21-
return JSON.stringify(id) + ": 0";
22-
}).join(",\n")
23-
),
24-
"};"
25-
]);
26-
}
27-
return source;
28-
});
29-
mainTemplate.plugin("jsonp-script", function(_, chunk, hash) {
30-
var chunkFilename = this.outputOptions.chunkFilename;
31-
var chunkMaps = chunk.getChunkMaps();
32-
var crossOriginLoading = this.outputOptions.crossOriginLoading;
33-
var chunkLoadTimeout = this.outputOptions.chunkLoadTimeout || 120000;
34-
return this.asString([
35-
"var script = document.createElement('script');",
36-
"script.type = 'text/javascript';",
37-
"script.charset = 'utf-8';",
38-
"script.async = true;",
39-
"script.timeout = " + chunkLoadTimeout + ";",
40-
crossOriginLoading ? "script.crossOrigin = '" + crossOriginLoading + "';" : "",
41-
"if (" + this.requireFn + ".nc) {",
42-
this.indent("script.setAttribute(\"nonce\", " + this.requireFn + ".nc);"),
43-
"}",
44-
"script.src = " + this.requireFn + ".p + " +
45-
this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
46-
hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"",
47-
hashWithLength: function(length) {
48-
return "\" + " + this.renderCurrentHashCode(hash, length) + " + \"";
49-
}.bind(this),
9+
class JsonpMainTemplatePlugin {
10+
11+
apply(mainTemplate) {
12+
mainTemplate.plugin("local-vars", function(source, chunk) {
13+
if(chunk.chunks.length > 0) {
14+
return this.asString([
15+
source,
16+
"",
17+
"// objects to store loaded and loading chunks",
18+
"var installedChunks = {",
19+
this.indent(
20+
chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n")
21+
),
22+
"};"
23+
]);
24+
}
25+
return source;
26+
});
27+
mainTemplate.plugin("jsonp-script", function(_, chunk, hash) {
28+
const chunkFilename = this.outputOptions.chunkFilename;
29+
const chunkMaps = chunk.getChunkMaps();
30+
const crossOriginLoading = this.outputOptions.crossOriginLoading;
31+
const chunkLoadTimeout = this.outputOptions.chunkLoadTimeout || 120000;
32+
const scriptSrcPath = this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
33+
hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
34+
hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
5035
chunk: {
5136
id: "\" + chunkId + \"",
52-
hash: "\" + " + JSON.stringify(chunkMaps.hash) + "[chunkId] + \"",
53-
hashWithLength: function(length) {
54-
var shortChunkHashMap = {};
55-
Object.keys(chunkMaps.hash).forEach(function(chunkId) {
37+
hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
38+
hashWithLength(length) {
39+
const shortChunkHashMap = Object.create(null);
40+
Object.keys(chunkMaps.hash).forEach(chunkId => {
5641
if(typeof chunkMaps.hash[chunkId] === "string")
5742
shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length);
5843
});
59-
return "\" + " + JSON.stringify(shortChunkHashMap) + "[chunkId] + \"";
44+
return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`;
6045
},
61-
name: "\" + (" + JSON.stringify(chunkMaps.name) + "[chunkId]||chunkId) + \""
46+
name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`
6247
}
63-
}) + ";",
64-
"var timeout = setTimeout(onScriptComplete, " + chunkLoadTimeout + ");",
65-
"script.onerror = script.onload = onScriptComplete;",
66-
"function onScriptComplete() {",
67-
this.indent([
68-
"// avoid mem leaks in IE.",
69-
"script.onerror = script.onload = null;",
70-
"clearTimeout(timeout);",
71-
"var chunk = installedChunks[chunkId];",
72-
"if(chunk !== 0) {",
48+
});
49+
return this.asString([
50+
"var script = document.createElement('script');",
51+
"script.type = 'text/javascript';",
52+
"script.charset = 'utf-8';",
53+
"script.async = true;",
54+
`script.timeout = ${chunkLoadTimeout};`,
55+
crossOriginLoading ? `script.crossOrigin = ${JSON.stringify(crossOriginLoading)};` : "",
56+
`if (${this.requireFn}.nc) {`,
57+
this.indent(`script.setAttribute("nonce", ${this.requireFn}.nc);`),
58+
"}",
59+
`script.src = ${this.requireFn}.p + ${scriptSrcPath};`,
60+
`var timeout = setTimeout(onScriptComplete, ${chunkLoadTimeout});`,
61+
"script.onerror = script.onload = onScriptComplete;",
62+
"function onScriptComplete() {",
7363
this.indent([
74-
"if(chunk) chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));",
75-
"installedChunks[chunkId] = undefined;"
64+
"// avoid mem leaks in IE.",
65+
"script.onerror = script.onload = null;",
66+
"clearTimeout(timeout);",
67+
"var chunk = installedChunks[chunkId];",
68+
"if(chunk !== 0) {",
69+
this.indent([
70+
"if(chunk) chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));",
71+
"installedChunks[chunkId] = undefined;"
72+
]),
73+
"}"
7674
]),
77-
"}"
78-
]),
79-
"};",
80-
]);
81-
});
82-
mainTemplate.plugin("require-ensure", function(_, chunk, hash) {
83-
return this.asString([
84-
"if(installedChunks[chunkId] === 0)",
85-
this.indent([
86-
"return Promise.resolve();"
87-
]),
88-
"",
89-
"// a Promise means \"currently loading\".",
90-
"if(installedChunks[chunkId]) {",
91-
this.indent([
92-
"return installedChunks[chunkId][2];"
93-
]),
94-
"}",
95-
"",
96-
"// setup Promise in chunk cache",
97-
"var promise = new Promise(function(resolve, reject) {",
98-
this.indent([
99-
"installedChunks[chunkId] = [resolve, reject];"
100-
]),
101-
"});",
102-
"installedChunks[chunkId][2] = promise;",
103-
"",
104-
"// start chunk loading",
105-
"var head = document.getElementsByTagName('head')[0];",
106-
this.applyPluginsWaterfall("jsonp-script", "", chunk, hash),
107-
"head.appendChild(script);",
108-
"",
109-
"return promise;"
110-
]);
111-
});
112-
mainTemplate.plugin("require-extensions", function(source, chunk) {
113-
if(chunk.chunks.length === 0) return source;
114-
return this.asString([
115-
source,
116-
"",
117-
"// on error function for async loading",
118-
this.requireFn + ".oe = function(err) { console.error(err); throw err; };"
119-
]);
120-
});
121-
mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
122-
if(chunk.chunks.length > 0) {
123-
var jsonpFunction = this.outputOptions.jsonpFunction;
75+
"};",
76+
]);
77+
});
78+
mainTemplate.plugin("require-ensure", function(_, chunk, hash) {
12479
return this.asString([
125-
source,
80+
"if(installedChunks[chunkId] === 0)",
81+
this.indent([
82+
"return Promise.resolve();"
83+
]),
12684
"",
127-
"// install a JSONP callback for chunk loading",
128-
"var parentJsonpFunction = window[" + JSON.stringify(jsonpFunction) + "];",
129-
"window[" + JSON.stringify(jsonpFunction) + "] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {",
85+
"// a Promise means \"currently loading\".",
86+
"if(installedChunks[chunkId]) {",
13087
this.indent([
131-
"// add \"moreModules\" to the modules object,",
132-
"// then flag all \"chunkIds\" as loaded and fire callback",
133-
"var moduleId, chunkId, i = 0, resolves = [], result;",
134-
"for(;i < chunkIds.length; i++) {",
135-
this.indent([
136-
"chunkId = chunkIds[i];",
137-
"if(installedChunks[chunkId])",
138-
this.indent("resolves.push(installedChunks[chunkId][0]);"),
139-
"installedChunks[chunkId] = 0;"
140-
]),
141-
"}",
142-
"for(moduleId in moreModules) {",
88+
"return installedChunks[chunkId][2];"
89+
]),
90+
"}",
91+
"",
92+
"// setup Promise in chunk cache",
93+
"var promise = new Promise(function(resolve, reject) {",
94+
this.indent([
95+
"installedChunks[chunkId] = [resolve, reject];"
96+
]),
97+
"});",
98+
"installedChunks[chunkId][2] = promise;",
99+
"",
100+
"// start chunk loading",
101+
"var head = document.getElementsByTagName('head')[0];",
102+
this.applyPluginsWaterfall("jsonp-script", "", chunk, hash),
103+
"head.appendChild(script);",
104+
"",
105+
"return promise;"
106+
]);
107+
});
108+
mainTemplate.plugin("require-extensions", function(source, chunk) {
109+
if(chunk.chunks.length === 0) return source;
110+
111+
return this.asString([
112+
source,
113+
"",
114+
"// on error function for async loading",
115+
`${this.requireFn}.oe = function(err) { console.error(err); throw err; };`
116+
]);
117+
});
118+
mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
119+
if(chunk.chunks.length > 0) {
120+
var jsonpFunction = this.outputOptions.jsonpFunction;
121+
return this.asString([
122+
source,
123+
"",
124+
"// install a JSONP callback for chunk loading",
125+
`var parentJsonpFunction = window[${JSON.stringify(jsonpFunction)}];`,
126+
`window[${JSON.stringify(jsonpFunction)}] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {`,
143127
this.indent([
144-
"if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {",
145-
this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
146-
"}"
147-
]),
148-
"}",
149-
"if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);",
150-
"while(resolves.length)",
151-
this.indent("resolves.shift()();"),
152-
this.entryPointInChildren(chunk) ? [
153-
"if(executeModules) {",
128+
"// add \"moreModules\" to the modules object,",
129+
"// then flag all \"chunkIds\" as loaded and fire callback",
130+
"var moduleId, chunkId, i = 0, resolves = [], result;",
131+
"for(;i < chunkIds.length; i++) {",
154132
this.indent([
155-
"for(i=0; i < executeModules.length; i++) {",
156-
this.indent("result = " + this.requireFn + "(" + this.requireFn + ".s = executeModules[i]);"),
133+
"chunkId = chunkIds[i];",
134+
"if(installedChunks[chunkId])",
135+
this.indent("resolves.push(installedChunks[chunkId][0]);"),
136+
"installedChunks[chunkId] = 0;"
137+
]),
138+
"}",
139+
"for(moduleId in moreModules) {",
140+
this.indent([
141+
"if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {",
142+
this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
157143
"}"
158144
]),
159145
"}",
160-
"return result;",
161-
] : ""
162-
]),
163-
"};"
164-
]);
165-
}
166-
return source;
167-
});
168-
mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) {
169-
var hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename;
170-
var hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename;
171-
var hotUpdateFunction = this.outputOptions.hotUpdateFunction;
172-
var currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
173-
hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"",
174-
hashWithLength: function(length) {
175-
return "\" + " + this.renderCurrentHashCode(hash, length) + " + \"";
176-
}.bind(this),
177-
chunk: {
178-
id: "\" + chunkId + \""
146+
"if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);",
147+
"while(resolves.length)",
148+
this.indent("resolves.shift()();"),
149+
this.entryPointInChildren(chunk) ? [
150+
"if(executeModules) {",
151+
this.indent([
152+
"for(i=0; i < executeModules.length; i++) {",
153+
this.indent(`result = ${this.requireFn}(${this.requireFn}.s = executeModules[i]);`),
154+
"}"
155+
]),
156+
"}",
157+
"return result;",
158+
] : ""
159+
]),
160+
"};"
161+
]);
179162
}
163+
return source;
180164
});
181-
var currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
182-
hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"",
183-
hashWithLength: function(length) {
184-
return "\" + " + this.renderCurrentHashCode(hash, length) + " + \"";
185-
}.bind(this)
165+
mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) {
166+
const hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename;
167+
const hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename;
168+
const hotUpdateFunction = this.outputOptions.hotUpdateFunction;
169+
const currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
170+
hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
171+
hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
172+
chunk: {
173+
id: "\" + chunkId + \""
174+
}
175+
});
176+
const currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
177+
hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
178+
hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`
179+
});
180+
const runtimeSource = Template.getFunctionContent(require("./JsonpMainTemplate.runtime.js"))
181+
.replace(/\/\/\$semicolon/g, ";")
182+
.replace(/\$require\$/g, this.requireFn)
183+
.replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename)
184+
.replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename)
185+
.replace(/\$hash\$/g, JSON.stringify(hash));
186+
return `${source}
187+
function hotDisposeChunk(chunkId) {
188+
delete installedChunks[chunkId];
189+
}
190+
var parentHotUpdateCallback = this[${JSON.stringify(hotUpdateFunction)}];
191+
this[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`;
186192
});
187-
188-
return source + "\n" +
189-
"function hotDisposeChunk(chunkId) {\n" +
190-
"\tdelete installedChunks[chunkId];\n" +
191-
"}\n" +
192-
"var parentHotUpdateCallback = this[" + JSON.stringify(hotUpdateFunction) + "];\n" +
193-
"this[" + JSON.stringify(hotUpdateFunction) + "] = " + Template.getFunctionContent(require("./JsonpMainTemplate.runtime.js"))
194-
.replace(/\/\/\$semicolon/g, ";")
195-
.replace(/\$require\$/g, this.requireFn)
196-
.replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename)
197-
.replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename)
198-
.replace(/\$hash\$/g, JSON.stringify(hash));
199-
});
200-
mainTemplate.plugin("hash", function(hash) {
201-
hash.update("jsonp");
202-
hash.update("4");
203-
hash.update(this.outputOptions.filename + "");
204-
hash.update(this.outputOptions.chunkFilename + "");
205-
hash.update(this.outputOptions.jsonpFunction + "");
206-
hash.update(this.outputOptions.hotUpdateFunction + "");
207-
});
208-
};
193+
mainTemplate.plugin("hash", function(hash) {
194+
hash.update("jsonp");
195+
hash.update("4");
196+
hash.update(`${this.outputOptions.filename}`);
197+
hash.update(`${this.outputOptions.chunkFilename}`);
198+
hash.update(`${this.outputOptions.jsonpFunction}`);
199+
hash.update(`${this.outputOptions.hotUpdateFunction}`);
200+
});
201+
}
202+
}
203+
module.exports = JsonpMainTemplatePlugin;

0 commit comments

Comments
 (0)