APIPlugin.js
2.2 KB
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
79
80
81
82
83
84
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConstDependency = require("./dependencies/ConstDependency");
const ParserHelpers = require("./ParserHelpers");
const NullFactory = require("./NullFactory");
/* eslint-disable camelcase */
const REPLACEMENTS = {
__webpack_require__: "__webpack_require__",
__webpack_public_path__: "__webpack_require__.p",
__webpack_modules__: "__webpack_require__.m",
__webpack_chunk_load__: "__webpack_require__.e",
__non_webpack_require__: "require",
__webpack_nonce__: "__webpack_require__.nc",
"require.onError": "__webpack_require__.oe"
};
const NO_WEBPACK_REQUIRE = {
__non_webpack_require__: true
};
const REPLACEMENT_TYPES = {
__webpack_public_path__: "string",
__webpack_require__: "function",
__webpack_modules__: "object",
__webpack_chunk_load__: "function",
__webpack_nonce__: "string"
};
/* eslint-enable camelcase */
class APIPlugin {
apply(compiler) {
compiler.hooks.compilation.tap(
"APIPlugin",
(compilation, { normalModuleFactory }) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(
ConstDependency,
new ConstDependency.Template()
);
const handler = parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.hooks.expression
.for(key)
.tap(
"APIPlugin",
NO_WEBPACK_REQUIRE[key]
? ParserHelpers.toConstantDependency(
parser,
REPLACEMENTS[key]
)
: ParserHelpers.toConstantDependencyWithWebpackRequire(
parser,
REPLACEMENTS[key]
)
);
const type = REPLACEMENT_TYPES[key];
if (type) {
parser.hooks.evaluateTypeof
.for(key)
.tap("APIPlugin", ParserHelpers.evaluateToString(type));
}
});
};
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("APIPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("APIPlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/esm")
.tap("APIPlugin", handler);
}
);
}
}
module.exports = APIPlugin;