webpack/lib/ConstPlugin.js

67 lines
2.4 KiB
JavaScript
Raw Normal View History

2013-01-31 01:49:25 +08:00
/*
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");
2013-01-31 01:49:25 +08:00
const getQuery = (request) => {
const i = request.indexOf("?");
return request.indexOf("?") < 0 ? "" : request.substr(i);
2017-01-11 17:51:58 +08:00
};
class ConstPlugin {
apply(compiler) {
2017-12-06 22:01:25 +08:00
compiler.hooks.compilation.tap("ConstPlugin", (compilation, {
normalModuleFactory
}) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
const handler = parser => {
parser.hooks.statementIf.tap("ConstPlugin", statement => {
2017-11-08 18:32:05 +08:00
const param = parser.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;
2017-11-08 18:32:05 +08:00
parser.state.current.addDependency(dep);
}
return bool;
}
});
parser.hooks.expressionConditionalOperator.tap("ConstPlugin", expression => {
2017-11-08 18:32:05 +08:00
const param = parser.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;
2017-11-08 18:32:05 +08:00
parser.state.current.addDependency(dep);
}
return bool;
}
});
parser.hooks.evaluateIdentifier.for("__resourceQuery").tap("ConstPlugin", expr => {
2017-11-08 18:32:05 +08:00
if(!parser.state.module) return;
return ParserHelpers.evaluateToString(getQuery(parser.state.module.resource))(expr);
});
parser.hooks.expression.for("__resourceQuery").tap("ConstPlugin", () => {
2017-11-08 18:32:05 +08:00
if(!parser.state.module) return;
parser.state.current.addVariable("__resourceQuery", JSON.stringify(getQuery(parser.state.module.resource)));
return true;
});
};
normalModuleFactory.hooks.parser.for("javascript/auto").tap("ConstPlugin", handler);
normalModuleFactory.hooks.parser.for("javascript/dynamic").tap("ConstPlugin", handler);
normalModuleFactory.hooks.parser.for("javascript/esm").tap("ConstPlugin", handler);
});
}
}
module.exports = ConstPlugin;