-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
78 lines (71 loc) · 2.48 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*!
* ExternalTemplateRemotesPlugin
* License: MIT (https://mit-license.org/)
*/
const extractUrlAndGlobal = require('webpack/lib/util/extractUrlAndGlobal');
const { RawSource } = require('webpack-sources');
const PLUGIN_NAME = 'ExternalTemplateRemotesPlugin';
class ExternalTemplateRemotesPlugin {
apply(compiler) {
compiler.hooks.make.tap(PLUGIN_NAME, compilation => {
const scriptExternalModules = [];
compilation.hooks.buildModule.tap(PLUGIN_NAME, module => {
if (module.constructor.name === 'ExternalModule' && module.externalType === 'script') {
scriptExternalModules.push(module);
}
});
compilation.hooks.afterCodeGeneration.tap(PLUGIN_NAME, function() {
scriptExternalModules.map(module => {
const urlTemplate = extractUrlAndGlobal(module.request)[0];
const urlExpression = toExpression(urlTemplate);
const sourceMap = compilation.codeGenerationResults.get(module).sources;
const rawSource = sourceMap.get('javascript');
sourceMap.set(
'javascript',
new RawSource(rawSource.source().replace(`"${urlTemplate}"`, urlExpression))
);
});
});
});
}
}
function toExpression(templateUrl) {
const result = [];
const current = [];
let isExpression = false;
let invalid = false;
for (const c of templateUrl) {
if (c === '[') {
if (isExpression) {
invalid = true;
break;
}
isExpression = true;
if (current.length) {
result.push(`"${current.join('')}"`);
current.length = 0;
}
} else if (c === ']') {
if (!isExpression) {
invalid = true;
break;
}
isExpression = false;
if (current.length) {
result.push(`${current.join('')}`);
current.length = 0;
}
current.length = 0;
} else {
current.push(c);
}
}
if (isExpression || invalid) {
throw new Error(`Invalid template URL "${templateUrl}"`);
}
if (current.length) {
result.push(`"${current.join('')}"`);
}
return result.join(' + ');
}
module.exports = ExternalTemplateRemotesPlugin;