RequireContextDependencyParserPlugin.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
  8. /** @typedef {import("../javascript/JavascriptParser")} JavascriptParser */
  9. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  10. module.exports = class RequireContextDependencyParserPlugin {
  11. /**
  12. * @param {JavascriptParser} parser the parser
  13. * @returns {void}
  14. */
  15. apply(parser) {
  16. parser.hooks.call
  17. .for("require.context")
  18. .tap("RequireContextDependencyParserPlugin", expr => {
  19. let regExp = /^\.\/.*$/;
  20. let recursive = true;
  21. let mode = "sync";
  22. switch (expr.arguments.length) {
  23. case 4: {
  24. const modeExpr = parser.evaluateExpression(expr.arguments[3]);
  25. if (!modeExpr.isString()) return;
  26. mode = /** @type {string} */ (modeExpr.string);
  27. }
  28. // falls through
  29. case 3: {
  30. const regExpExpr = parser.evaluateExpression(expr.arguments[2]);
  31. if (!regExpExpr.isRegExp()) return;
  32. regExp = /** @type {RegExp} */ (regExpExpr.regExp);
  33. }
  34. // falls through
  35. case 2: {
  36. const recursiveExpr = parser.evaluateExpression(expr.arguments[1]);
  37. if (!recursiveExpr.isBoolean()) return;
  38. recursive = /** @type {boolean} */ (recursiveExpr.bool);
  39. }
  40. // falls through
  41. case 1: {
  42. const requestExpr = parser.evaluateExpression(expr.arguments[0]);
  43. if (!requestExpr.isString()) return;
  44. const dep = new RequireContextDependency(
  45. {
  46. request: requestExpr.string,
  47. recursive,
  48. regExp,
  49. mode,
  50. category: "commonjs"
  51. },
  52. /** @type {Range} */ (expr.range)
  53. );
  54. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  55. dep.optional = !!parser.scope.inTry;
  56. parser.state.current.addDependency(dep);
  57. return true;
  58. }
  59. }
  60. });
  61. }
  62. };