Skip to content

Commit

Permalink
+ Added no-index-import rule to prevent cyclic imports
Browse files Browse the repository at this point in the history
  • Loading branch information
Justin99b committed Mar 2, 2023
1 parent 5680a1f commit f71f6ba
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export const rules = {
'consistent-type-specifier-style': require('./rules/consistent-type-specifier-style'),

'no-self-import': require('./rules/no-self-import'),
'no-index-import': require('./rules/no-index-import'),
'no-cycle': require('./rules/no-cycle'),
'no-named-default': require('./rules/no-named-default'),
'no-named-as-default': require('./rules/no-named-as-default'),
Expand Down
40 changes: 40 additions & 0 deletions src/rules/no-index-import.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* @fileOverview Forbids a module from importing itself
* @author Gio d'Amelio
*/

import resolve from 'eslint-module-utils/resolve';
import moduleVisitor from 'eslint-module-utils/moduleVisitor';
import docsUrl from '../docsUrl';

var path = require('path');
const isIndexRegex = /index\.(ts|js)/;
const isNodeModuleRegex = /node_modules/;

module.exports = {
meta: {
type: 'problem',
docs: {
category: 'Static analysis',
description: 'Forbid a module to import any index to prevent cyclic imports',
recommended: false,
url: docsUrl('no-index-import'),
},
schema: [],
},
create(context) {
return moduleVisitor((source, node) => {
const filePath = context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename();
const fileName = path.basename(filePath);
const resolved = resolve(source.value, context);
const resolveFileName = path.basename(resolved);

if (!isNodeModuleRegex.test(resolved) && !isIndexRegex.test(fileName) && isIndexRegex.test(resolveFileName)) {
context.report({
node,
message: 'Index imports are not allowed',
});
}
}, {commonjs: true});
},
};

0 comments on commit f71f6ba

Please sign in to comment.