global-require.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * @author Jamund Ferguson
  3. * See LICENSE file in root directory for full license.
  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(
  24. reference =>
  25. reference.identifier.range[0] === node.range[0] &&
  26. reference.identifier.range[1] === node.range[1]
  27. )
  28. /* istanbul ignore else: correctly returns null */
  29. if (references.length === 1) {
  30. return references[0]
  31. }
  32. return null
  33. }
  34. /**
  35. * Checks if the given identifier node is shadowed in the given scope.
  36. * @param {Object} scope The current scope.
  37. * @param {ASTNode} node The identifier node to check.
  38. * @returns {boolean} Whether or not the name is shadowed.
  39. */
  40. function isShadowed(scope, node) {
  41. const reference = findReference(scope, node)
  42. return reference && reference.resolved && reference.resolved.defs.length > 0
  43. }
  44. module.exports = {
  45. meta: {
  46. type: "suggestion",
  47. docs: {
  48. description:
  49. "require `require()` calls to be placed at top-level module scope",
  50. category: "Stylistic Issues",
  51. recommended: false,
  52. url: "https://github.com/weiran-zsd/eslint-plugin-node/blob/HEAD/docs/rules/global-require.md",
  53. },
  54. fixable: null,
  55. schema: [],
  56. messages: {
  57. unexpected: "Unexpected require().",
  58. },
  59. },
  60. create(context) {
  61. return {
  62. CallExpression(node) {
  63. const currentScope = context.getScope()
  64. if (
  65. node.callee.name === "require" &&
  66. !isShadowed(currentScope, node.callee)
  67. ) {
  68. const isGoodRequire = context
  69. .getAncestors()
  70. .every(
  71. parent =>
  72. ACCEPTABLE_PARENTS.indexOf(parent.type) > -1
  73. )
  74. if (!isGoodRequire) {
  75. context.report({ node, messageId: "unexpected" })
  76. }
  77. }
  78. },
  79. }
  80. },
  81. }