-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathprefer-aliased-path.ts
95 lines (84 loc) · 2.46 KB
/
prefer-aliased-path.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { readPackageUpSync, type ReadResult } from "read-package-up";
import { minimatch } from "minimatch";
import { createEslintRule } from "../utils";
export const RULE_NAME = "prefer-aliased-path";
export type MessageIds = "preferAliasedPath";
export type Options = [];
export default createEslintRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: "suggestion",
docs: {
description:
"Suggest using a package.json alias subpath import instead of a relative import.",
},
schema: [
{
type: "object",
additionalProperties: false,
properties: {},
},
],
messages: {
preferAliasedPath:
"Use an aliased path instead of a relative path for '{{ importPath }}'.",
},
},
defaultOptions: [],
create(context) {
let packageJson;
const sourceCode = context.getSourceCode();
sourceCode.ast.body.some((node) => {
if (node.type === "ImportDeclaration") {
const packagePath = node.source.value;
if (packagePath.startsWith(".")) {
const currentLocalDirectory = new URL(".", import.meta.url);
packageJson = readPackageUpSync({
cwd: currentLocalDirectory,
});
}
}
if (packageJson) {
return true;
}
});
if (!packageJson?.packageJson?.imports) {
return {};
}
return {
ImportDeclaration(node) {
if (node.type === "ImportDeclaration") {
const packagePath = node.source.value;
if (packagePath.startsWith(".")) {
const importAliases = Object.values(
packageJson.packageJson.imports,
);
for (const importAlias of importAliases) {
if (!importAlias || typeof importAlias !== "string") {
continue;
}
const capturedExtension = importAlias.endsWith(".ts")
? ".ts"
: importAlias.endsWith(".js")
? ".js"
: "";
const isPathMatched = minimatch(
`${packagePath}${capturedExtension}`,
importAlias,
);
if (isPathMatched) {
context.report({
node,
messageId: "preferAliasedPath",
data: {
importPath: packagePath,
},
});
}
}
}
}
},
};
},
});