ConstPlugin.js
2.01 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
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConstDependency = require("./dependencies/ConstDependency");
const NullFactory = require("./NullFactory");
const ParserHelpers = require("./ParserHelpers");
const getQuery = (request) => {
const i = request.indexOf("?");
return request.indexOf("?") < 0 ? "" : request.substr(i);
};
class ConstPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
parser.plugin("statement if", function(statement) {
const param = this.evaluateExpression(statement.test);
const bool = param.asBool();
if(typeof bool === "boolean") {
if(statement.test.type !== "Literal") {
const dep = new ConstDependency(`${bool}`, param.range);
dep.loc = statement.loc;
this.state.current.addDependency(dep);
}
return bool;
}
});
parser.plugin("expression ?:", function(expression) {
const param = this.evaluateExpression(expression.test);
const bool = param.asBool();
if(typeof bool === "boolean") {
if(expression.test.type !== "Literal") {
const dep = new ConstDependency(` ${bool}`, param.range);
dep.loc = expression.loc;
this.state.current.addDependency(dep);
}
return bool;
}
});
parser.plugin("evaluate Identifier __resourceQuery", function(expr) {
if(!this.state.module) return;
return ParserHelpers.evaluateToString(getQuery(this.state.module.resource))(expr);
});
parser.plugin("expression __resourceQuery", function() {
if(!this.state.module) return;
this.state.current.addVariable("__resourceQuery", JSON.stringify(getQuery(this.state.module.resource)));
return true;
});
});
});
}
}
module.exports = ConstPlugin;