2 * @fileoverview Rule for disallowing require() outside of the top-level module context
3 * @author Jamund Ferguson
8 const ACCEPTABLE_PARENTS = [
9 "AssignmentExpression",
12 "ExpressionStatement",
14 "ConditionalExpression",
16 "VariableDeclaration",
21 * Finds the eslint-scope reference in the given scope.
22 * @param {Object} scope The scope to search.
23 * @param {ASTNode} node The identifier node.
24 * @returns {Reference|null} Returns the found reference or null if none were found.
26 function findReference(scope, node) {
27 const references = scope.references.filter(reference => reference.identifier.range[0] === node.range[0] &&
28 reference.identifier.range[1] === node.range[1]);
30 /* istanbul ignore else: correctly returns null */
31 if (references.length === 1) {
39 * Checks if the given identifier node is shadowed in the given scope.
40 * @param {Object} scope The current scope.
41 * @param {ASTNode} node The identifier node to check.
42 * @returns {boolean} Whether or not the name is shadowed.
44 function isShadowed(scope, node) {
45 const reference = findReference(scope, node);
47 return reference && reference.resolved && reference.resolved.defs.length > 0;
59 description: "require `require()` calls to be placed at top-level module scope",
60 category: "Node.js and CommonJS",
62 url: "https://eslint.org/docs/rules/global-require"
67 unexpected: "Unexpected require()."
73 CallExpression(node) {
74 const currentScope = context.getScope();
76 if (node.callee.name === "require" && !isShadowed(currentScope, node.callee)) {
77 const isGoodRequire = context.getAncestors().every(parent => ACCEPTABLE_PARENTS.indexOf(parent.type) > -1);
80 context.report({ node, messageId: "unexpected" });