Skip to content

Commit

Permalink
fix(eslint-plugin): [no-require-imports] report only global 'require'
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelss95 committed Sep 12, 2021
1 parent 4a88de2 commit 6b08f54
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
39 changes: 34 additions & 5 deletions packages/eslint-plugin/src/rules/no-require-imports.ts
@@ -1,4 +1,4 @@
import { TSESTree } from '@typescript-eslint/experimental-utils';
import { TSESLint, TSESTree } from '@typescript-eslint/experimental-utils';
import * as util from '../util';

export default util.createRule({
Expand All @@ -21,10 +21,14 @@ export default util.createRule({
'CallExpression > Identifier[name="require"]'(
node: TSESTree.Identifier,
): void {
context.report({
node: node.parent!,
messageId: 'noRequireImports',
});
const variable = getVariableByName(context.getScope(), 'require');

if (!variable?.identifiers.length) {
context.report({
node,
messageId: 'noRequireImports',
});
}
},
TSExternalModuleReference(node): void {
context.report({
Expand All @@ -35,3 +39,28 @@ export default util.createRule({
};
},
});

/**
* Finds the variable by a given name in a given scope and its upper scopes.
* @param initScope A scope to start find.
* @param name A variable name to find.
* @returns A found variable or `null`.
*/
function getVariableByName(
initScope: TSESLint.Scope.Scope | null,
name: string,
): TSESLint.Scope.Variable | null {
let scope = initScope;

while (scope) {
const variable = scope.set.get(name);

if (variable) {
return variable;
}

scope = scope.upper;
}

return null;
}
5 changes: 5 additions & 0 deletions packages/eslint-plugin/tests/rules/no-require-imports.test.ts
Expand Up @@ -17,6 +17,11 @@ ruleTester.run('no-require-imports', rule, {
'import lib9 = lib2.anotherSubImport;',
"import lib10 from 'lib10';",
"var lib3 = load?.('not_an_import');",
`
import { createRequire } from 'module';
const require = createRequire();
require('remark-preset-prettier');
`,
],
invalid: [
{
Expand Down

0 comments on commit 6b08f54

Please sign in to comment.