1
|
/*
|
2
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
3
|
Author Tobias Koppers @sokra
|
4
|
*/
|
5
|
"use strict";
|
6
|
|
7
|
const Template = require("./Template");
|
8
|
const ConstDependency = require("./dependencies/ConstDependency");
|
9
|
const ParserHelpers = require("./ParserHelpers");
|
10
|
const NullFactory = require("./NullFactory");
|
11
|
|
12
|
const REPLACEMENTS = {
|
13
|
// eslint-disable-next-line camelcase
|
14
|
__webpack_hash__: "__webpack_require__.h",
|
15
|
// eslint-disable-next-line camelcase
|
16
|
__webpack_chunkname__: "__webpack_require__.cn"
|
17
|
};
|
18
|
const REPLACEMENT_TYPES = {
|
19
|
// eslint-disable-next-line camelcase
|
20
|
__webpack_hash__: "string",
|
21
|
// eslint-disable-next-line camelcase
|
22
|
__webpack_chunkname__: "string"
|
23
|
};
|
24
|
|
25
|
class ExtendedAPIPlugin {
|
26
|
apply(compiler) {
|
27
|
compiler.hooks.compilation.tap(
|
28
|
"ExtendedAPIPlugin",
|
29
|
(compilation, { normalModuleFactory }) => {
|
30
|
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
|
31
|
compilation.dependencyTemplates.set(
|
32
|
ConstDependency,
|
33
|
new ConstDependency.Template()
|
34
|
);
|
35
|
|
36
|
const mainTemplate = compilation.mainTemplate;
|
37
|
mainTemplate.hooks.requireExtensions.tap(
|
38
|
"ExtendedAPIPlugin",
|
39
|
(source, chunk, hash) => {
|
40
|
const buf = [source];
|
41
|
buf.push("");
|
42
|
buf.push("// __webpack_hash__");
|
43
|
buf.push(`${mainTemplate.requireFn}.h = ${JSON.stringify(hash)};`);
|
44
|
buf.push("");
|
45
|
buf.push("// __webpack_chunkname__");
|
46
|
buf.push(
|
47
|
`${mainTemplate.requireFn}.cn = ${JSON.stringify(chunk.name)};`
|
48
|
);
|
49
|
return Template.asString(buf);
|
50
|
}
|
51
|
);
|
52
|
mainTemplate.hooks.globalHash.tap("ExtendedAPIPlugin", () => true);
|
53
|
|
54
|
const handler = (parser, parserOptions) => {
|
55
|
Object.keys(REPLACEMENTS).forEach(key => {
|
56
|
parser.hooks.expression
|
57
|
.for(key)
|
58
|
.tap(
|
59
|
"ExtendedAPIPlugin",
|
60
|
ParserHelpers.toConstantDependencyWithWebpackRequire(
|
61
|
parser,
|
62
|
REPLACEMENTS[key]
|
63
|
)
|
64
|
);
|
65
|
parser.hooks.evaluateTypeof
|
66
|
.for(key)
|
67
|
.tap(
|
68
|
"ExtendedAPIPlugin",
|
69
|
ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key])
|
70
|
);
|
71
|
});
|
72
|
};
|
73
|
|
74
|
normalModuleFactory.hooks.parser
|
75
|
.for("javascript/auto")
|
76
|
.tap("ExtendedAPIPlugin", handler);
|
77
|
normalModuleFactory.hooks.parser
|
78
|
.for("javascript/dynamic")
|
79
|
.tap("ExtendedAPIPlugin", handler);
|
80
|
normalModuleFactory.hooks.parser
|
81
|
.for("javascript/esm")
|
82
|
.tap("ExtendedAPIPlugin", handler);
|
83
|
}
|
84
|
);
|
85
|
}
|
86
|
}
|
87
|
|
88
|
module.exports = ExtendedAPIPlugin;
|