ConstPlugin.js 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const ConstDependency = require("./dependencies/ConstDependency");
  7. const NullFactory = require("./NullFactory");
  8. const ParserHelpers = require("./ParserHelpers");
  9. const getQuery = (request) => {
  10. const i = request.indexOf("?");
  11. return request.indexOf("?") < 0 ? "" : request.substr(i);
  12. };
  13. class ConstPlugin {
  14. apply(compiler) {
  15. compiler.plugin("compilation", (compilation, params) => {
  16. compilation.dependencyFactories.set(ConstDependency, new NullFactory());
  17. compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
  18. params.normalModuleFactory.plugin("parser", parser => {
  19. parser.plugin("statement if", function(statement) {
  20. const param = this.evaluateExpression(statement.test);
  21. const bool = param.asBool();
  22. if(typeof bool === "boolean") {
  23. if(statement.test.type !== "Literal") {
  24. const dep = new ConstDependency(`${bool}`, param.range);
  25. dep.loc = statement.loc;
  26. this.state.current.addDependency(dep);
  27. }
  28. return bool;
  29. }
  30. });
  31. parser.plugin("expression ?:", function(expression) {
  32. const param = this.evaluateExpression(expression.test);
  33. const bool = param.asBool();
  34. if(typeof bool === "boolean") {
  35. if(expression.test.type !== "Literal") {
  36. const dep = new ConstDependency(` ${bool}`, param.range);
  37. dep.loc = expression.loc;
  38. this.state.current.addDependency(dep);
  39. }
  40. return bool;
  41. }
  42. });
  43. parser.plugin("evaluate Identifier __resourceQuery", function(expr) {
  44. if(!this.state.module) return;
  45. return ParserHelpers.evaluateToString(getQuery(this.state.module.resource))(expr);
  46. });
  47. parser.plugin("expression __resourceQuery", function() {
  48. if(!this.state.module) return;
  49. this.state.current.addVariable("__resourceQuery", JSON.stringify(getQuery(this.state.module.resource)));
  50. return true;
  51. });
  52. });
  53. });
  54. }
  55. }
  56. module.exports = ConstPlugin;