global-require.js 2.4 KB

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