1
|
/*
|
2
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
3
|
Author Tobias Koppers @sokra
|
4
|
*/
|
5
|
"use strict";
|
6
|
|
7
|
const ParserHelpers = require("./ParserHelpers");
|
8
|
const ConstDependency = require("./dependencies/ConstDependency");
|
9
|
|
10
|
const NullFactory = require("./NullFactory");
|
11
|
|
12
|
class ProvidePlugin {
|
13
|
constructor(definitions) {
|
14
|
this.definitions = definitions;
|
15
|
}
|
16
|
|
17
|
apply(compiler) {
|
18
|
const definitions = this.definitions;
|
19
|
compiler.hooks.compilation.tap(
|
20
|
"ProvidePlugin",
|
21
|
(compilation, { normalModuleFactory }) => {
|
22
|
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
|
23
|
compilation.dependencyTemplates.set(
|
24
|
ConstDependency,
|
25
|
new ConstDependency.Template()
|
26
|
);
|
27
|
const handler = (parser, parserOptions) => {
|
28
|
Object.keys(definitions).forEach(name => {
|
29
|
var request = [].concat(definitions[name]);
|
30
|
var splittedName = name.split(".");
|
31
|
if (splittedName.length > 0) {
|
32
|
splittedName.slice(1).forEach((_, i) => {
|
33
|
const name = splittedName.slice(0, i + 1).join(".");
|
34
|
parser.hooks.canRename
|
35
|
.for(name)
|
36
|
.tap("ProvidePlugin", ParserHelpers.approve);
|
37
|
});
|
38
|
}
|
39
|
parser.hooks.expression.for(name).tap("ProvidePlugin", expr => {
|
40
|
let nameIdentifier = name;
|
41
|
const scopedName = name.includes(".");
|
42
|
let expression = `require(${JSON.stringify(request[0])})`;
|
43
|
if (scopedName) {
|
44
|
nameIdentifier = `__webpack_provided_${name.replace(
|
45
|
/\./g,
|
46
|
"_dot_"
|
47
|
)}`;
|
48
|
}
|
49
|
if (request.length > 1) {
|
50
|
expression += request
|
51
|
.slice(1)
|
52
|
.map(r => `[${JSON.stringify(r)}]`)
|
53
|
.join("");
|
54
|
}
|
55
|
if (
|
56
|
!ParserHelpers.addParsedVariableToModule(
|
57
|
parser,
|
58
|
nameIdentifier,
|
59
|
expression
|
60
|
)
|
61
|
) {
|
62
|
return false;
|
63
|
}
|
64
|
if (scopedName) {
|
65
|
ParserHelpers.toConstantDependency(
|
66
|
parser,
|
67
|
nameIdentifier
|
68
|
)(expr);
|
69
|
}
|
70
|
return true;
|
71
|
});
|
72
|
});
|
73
|
};
|
74
|
normalModuleFactory.hooks.parser
|
75
|
.for("javascript/auto")
|
76
|
.tap("ProvidePlugin", handler);
|
77
|
normalModuleFactory.hooks.parser
|
78
|
.for("javascript/dynamic")
|
79
|
.tap("ProvidePlugin", handler);
|
80
|
|
81
|
// Disable ProvidePlugin for javascript/esm, see https://github.com/webpack/webpack/issues/7032
|
82
|
}
|
83
|
);
|
84
|
}
|
85
|
}
|
86
|
module.exports = ProvidePlugin;
|