-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck-path-alias.js
76 lines (70 loc) · 2.57 KB
/
check-path-alias.js
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
/**
* @fileoverview Check if imports match the path aliases defined in tsconfig.
*/
"use strict";
const path = require("path");
module.exports = {
meta: {
type: "problem",
docs: {
description:
"Check if imports match the path aliases defined in tsconfig",
category: "Possible Errors",
recommended: true,
},
fixable: "code",
schema: [],
},
create: function (context) {
return {
ImportDeclaration(node) {
const importPath = node.source.value;
// Get aliases from tsconfig and check if the import matches any of them
// "paths": {
// "src/*": ["src/*"],
// "@assets/*": ["src/assets/*"],
// "@pages/*": ["src/pages/*"],
// "@public/*": ["public/*"],
// "@shared/*": ["src/shared/*"],
// "@views/*": ["src/views/*"]
// }
const tsconfig = require(path.resolve(
process.cwd(),
"tsconfig.json"
));
const paths = tsconfig.compilerOptions.paths;
let pathList = [];
for (let key in paths) {
paths[key].forEach((value) => {
if (key.startsWith("@")) {
pathList.push(value.replace("/*", ""));
}
});
}
if (pathList.some((path) => importPath.startsWith(path))) {
const matchingPath = pathList.find((path) =>
importPath.startsWith(path)
);
const alias = Object.keys(paths).find((key) =>
paths[key].includes(matchingPath + "/*")
);
const aliasParsed = alias.replace("/*", "");
const updatedImportPath = importPath.replace(
matchingPath,
aliasParsed
);
context.report({
node,
message: `Run autofix to use path alias: ${alias}`,
fix: (fixer) => {
return fixer.replaceText(
node.source,
`'${updatedImportPath}'`
);
},
});
}
},
};
},
};