-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
110 lines (104 loc) · 2.74 KB
/
index.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
'use strict';
const fs = require('fs');
const path = require('path');
const DEFAULTS = {
allowShorterRelative: false,
};
const getOptions = (context) => {
const option = context.options[0] || {};
return {
allowShorterRelative:
option.allowShorterRelative !== undefined
? option.allowShorterRelative
: DEFAULTS.allowShorterRelative,
};
};
const getBaseUrl = () => {
const fromFile = (name) => {
const file = JSON.parse(fs.readFileSync(name));
if (file.compilerOptions && file.compilerOptions.baseUrl) {
return file.compilerOptions.baseUrl;
}
};
if (fs.existsSync('tsconfig.json')) {
return fromFile('tsconfig.json');
}
if (fs.existsSync('jsconfig.json')) {
return fromFile('jsconfig.json');
}
return './src';
};
const create = (context) => {
const baseUrl = getBaseUrl();
const { allowShorterRelative } = getOptions(context);
const root = path.resolve(process.cwd(), baseUrl);
return {
ImportDeclaration(node) {
const { value: target } = node.source;
if (target.startsWith('../')) {
const sourcePath = context.getFilename();
const targetPath = path.resolve(path.dirname(sourcePath), target);
const absoluteSource = path.relative(root, sourcePath);
const absoluteTarget = path.relative(root, targetPath);
if (absoluteSource.split('/')[0] !== absoluteTarget.split('/')[0]) {
context.report({
node,
message: `Use absolute import "${absoluteTarget}"`,
fix: (fixer) => {
return fixer.replaceText(node.source, `'${absoluteTarget}'`);
},
});
} else if (
!allowShorterRelative ||
target.split('/').length >= absoluteTarget.split('/').length
) {
context.report({
node,
message: `Use absolute import "${absoluteTarget}"`,
fix: (fixer) => {
return fixer.replaceText(node.source, `'${absoluteTarget}'`);
},
});
}
}
},
};
};
module.exports = {
configs: {
recommended: {
plugins: ['enforce-absolute-imports'],
rules: {
'enforce-absolute-imports/imports': [
'error',
{
allowShorterRelative: true,
},
],
},
},
},
rules: {
imports: {
meta: {
docs: {
description: 'Enforce absolute imports',
category: 'Possible Errors',
recommended: true,
},
fixable: 'code',
schema: [
{
type: 'object',
properties: {
allowShorterRelative: {
type: 'boolean',
},
},
},
],
},
create,
},
},
};