UNPKG

1.42 kBJavaScriptView Raw
1const {extname, basename, relative, sep} = require('path');
2
3const resolve = require('eslint-module-utils/resolve').default;
4
5const {docsUrl} = require('../utilities');
6
7module.exports = {
8 meta: {
9 docs: {
10 description:
11 'Prefer that imports from within a directory extend to the file from where they are importing without relying on an index file.',
12 category: 'Best Practices',
13 recommended: false,
14 uri: docsUrl('no-ancestor-directory-import'),
15 },
16 fixable: null,
17 },
18 create(context) {
19 function isAncestorDirectoryImport(resolvedSource) {
20 const relativeDifference = relative(
21 context.getFilename(),
22 resolvedSource,
23 );
24
25 const parts = relativeDifference
26 .split(sep)
27 .filter((part) => part[0] !== '.');
28
29 if (parts.length > 1) {
30 return false;
31 }
32
33 return basename(parts[0], extname(parts[0])) === 'index';
34 }
35
36 return {
37 ImportDeclaration(node) {
38 const importSource = node.source.value;
39 const resolvedSource = resolve(importSource, context);
40
41 if (resolvedSource && isAncestorDirectoryImport(resolvedSource)) {
42 context.report({
43 node,
44 message:
45 'Ancestor imports should extend to the file from where they are importing without relying on an index file in the directory.',
46 });
47 }
48 },
49 };
50 },
51};