Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
epidemian
GitHub Repository: epidemian/eslint-plugin-import
Path: blob/main/src/rules/no-relative-parent-imports.js
829 views
1
import moduleVisitor, { makeOptionsSchema } from 'eslint-module-utils/moduleVisitor';
2
import docsUrl from '../docsUrl';
3
import { basename, dirname, relative } from 'path';
4
import resolve from 'eslint-module-utils/resolve';
5
6
import importType from '../core/importType';
7
8
module.exports = {
9
meta: {
10
type: 'suggestion',
11
docs: {
12
url: docsUrl('no-relative-parent-imports'),
13
},
14
schema: [makeOptionsSchema()],
15
},
16
17
create: function noRelativePackages(context) {
18
const myPath = context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename();
19
if (myPath === '<text>') return {}; // can't check a non-file
20
21
function checkSourceValue(sourceNode) {
22
const depPath = sourceNode.value;
23
24
if (importType(depPath, context) === 'external') { // ignore packages
25
return;
26
}
27
28
const absDepPath = resolve(depPath, context);
29
30
if (!absDepPath) { // unable to resolve path
31
return;
32
}
33
34
const relDepPath = relative(dirname(myPath), absDepPath);
35
36
if (importType(relDepPath, context) === 'parent') {
37
context.report({
38
node: sourceNode,
39
message: 'Relative imports from parent directories are not allowed. ' +
40
`Please either pass what you're importing through at runtime ` +
41
`(dependency injection), move \`${basename(myPath)}\` to same ` +
42
`directory as \`${depPath}\` or consider making \`${depPath}\` a package.`,
43
});
44
}
45
}
46
47
return moduleVisitor(checkSourceValue, context.options[0]);
48
},
49
};
50
51