RequireContextDependencyParserPlugin.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RequireContextDependency = require("./RequireContextDependency");
  7. module.exports = class RequireContextDependencyParserPlugin {
  8. apply(parser) {
  9. parser.hooks.call
  10. .for("require.context")
  11. .tap("RequireContextDependencyParserPlugin", expr => {
  12. let regExp = /^\.\/.*$/;
  13. let recursive = true;
  14. let mode = "sync";
  15. switch (expr.arguments.length) {
  16. case 4: {
  17. const modeExpr = parser.evaluateExpression(expr.arguments[3]);
  18. if (!modeExpr.isString()) return;
  19. mode = modeExpr.string;
  20. }
  21. // falls through
  22. case 3: {
  23. const regExpExpr = parser.evaluateExpression(expr.arguments[2]);
  24. if (!regExpExpr.isRegExp()) return;
  25. regExp = regExpExpr.regExp;
  26. }
  27. // falls through
  28. case 2: {
  29. const recursiveExpr = parser.evaluateExpression(expr.arguments[1]);
  30. if (!recursiveExpr.isBoolean()) return;
  31. recursive = recursiveExpr.bool;
  32. }
  33. // falls through
  34. case 1: {
  35. const requestExpr = parser.evaluateExpression(expr.arguments[0]);
  36. if (!requestExpr.isString()) return;
  37. const dep = new RequireContextDependency(
  38. {
  39. request: requestExpr.string,
  40. recursive,
  41. regExp,
  42. mode,
  43. category: "commonjs"
  44. },
  45. expr.range
  46. );
  47. dep.loc = expr.loc;
  48. dep.optional = !!parser.scope.inTry;
  49. parser.state.current.addDependency(dep);
  50. return true;
  51. }
  52. }
  53. });
  54. }
  55. };