Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

global-require.js 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * @fileoverview Rule for disallowing require() outside of the top-level module context
  3. * @author Jamund Ferguson
  4. */
  5. "use strict";
  6. const ACCEPTABLE_PARENTS = [
  7. "AssignmentExpression",
  8. "VariableDeclarator",
  9. "MemberExpression",
  10. "ExpressionStatement",
  11. "CallExpression",
  12. "ConditionalExpression",
  13. "Program",
  14. "VariableDeclaration"
  15. ];
  16. /**
  17. * Finds the eslint-scope reference in the given scope.
  18. * @param {Object} scope The scope to search.
  19. * @param {ASTNode} node The identifier node.
  20. * @returns {Reference|null} Returns the found reference or null if none were found.
  21. */
  22. function findReference(scope, node) {
  23. const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] &&
  24. reference.identifier.range[1] === node.range[1]);
  25. /* istanbul ignore else: correctly returns null */
  26. if (references.length === 1) {
  27. return references[0];
  28. }
  29. return null;
  30. }
  31. /**
  32. * Checks if the given identifier node is shadowed in the given scope.
  33. * @param {Object} scope The current scope.
  34. * @param {ASTNode} node The identifier node to check.
  35. * @returns {boolean} Whether or not the name is shadowed.
  36. */
  37. function isShadowed(scope, node) {
  38. const reference = findReference(scope, node);
  39. return reference && reference.resolved && reference.resolved.defs.length > 0;
  40. }
  41. module.exports = {
  42. meta: {
  43. type: "suggestion",
  44. docs: {
  45. description: "require `require()` calls to be placed at top-level module scope",
  46. category: "Node.js and CommonJS",
  47. recommended: false,
  48. url: "https://eslint.org/docs/rules/global-require"
  49. },
  50. schema: []
  51. },
  52. create(context) {
  53. return {
  54. CallExpression(node) {
  55. const currentScope = context.getScope();
  56. if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) {
  57. const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1);
  58. if (!isGoodRequire) {
  59. context.report({ node, message: "Unexpected require()." });
  60. }
  61. }
  62. }
  63. };
  64. }
  65. };