0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-28 14:33:11 +01:00
nodejs/tools/eslint-rules/no-duplicate-requires.js
Aviv Keller 5c22d19f44
lib, tools: remove duplicate requires
PR-URL: https://github.com/nodejs/node/pull/54987
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
2024-09-25 08:51:28 +00:00

55 lines
1.4 KiB
JavaScript

/**
* @fileoverview Ensure modules are not required twice at top level of a module
* @author devsnek
* @author RedYetiDev
*/
'use strict';
const { isRequireCall, isString } = require('./rules-utils.js');
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const topLevelTypes = new Set([
'FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression',
'ClassBody', 'MethodDefinition',
]);
const isTopLevel = (node) => {
while (node) {
if (topLevelTypes.has(node.type)) return false;
node = node.parent;
}
return true;
};
module.exports = {
create(context) {
if (context.languageOptions.sourceType === 'module') {
return {};
}
const requiredModules = new Set();
return {
CallExpression(node) {
if (isRequireCall(node)) {
const [firstArg] = node.arguments;
if (isString(firstArg)) {
const moduleName = firstArg.value.trim();
if (requiredModules.has(moduleName)) {
context.report({
node,
message: `'${moduleName}' require is duplicated.`,
});
} else if (isTopLevel(node)) {
requiredModules.add(moduleName);
}
}
}
},
};
},
};