/
no-import-type-side-effects.ts
76 lines (70 loc) · 2.37 KB
/
no-import-type-side-effects.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
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as util from '../util';
type Options = [];
type MessageIds = 'useTopLevelQualifier';
export default util.createRule<Options, MessageIds>({
name: 'no-import-type-side-effects',
meta: {
type: 'problem',
docs: {
description:
'Enforce the use of top-level import type qualifier when an import only has specifiers with inline type qualifiers',
recommended: false,
},
fixable: 'code',
messages: {
useTopLevelQualifier:
'TypeScript will only remove the inline type specifiers which will leave behind a side effect import at runtime. Convert this to a top-level type qualifier to properly remove the entire import.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const sourceCode = context.getSourceCode();
return {
'ImportDeclaration[importKind!="type"]'(
node: TSESTree.ImportDeclaration,
): void {
const specifiers: TSESTree.ImportSpecifier[] = [];
for (const specifier of node.specifiers) {
if (
specifier.type !== AST_NODE_TYPES.ImportSpecifier ||
specifier.importKind !== 'type'
) {
return;
}
specifiers.push(specifier);
}
context.report({
node,
messageId: 'useTopLevelQualifier',
fix(fixer) {
const fixes: TSESLint.RuleFix[] = [];
for (const specifier of specifiers) {
const qualifier = util.nullThrows(
sourceCode.getFirstToken(specifier, util.isTypeKeyword),
util.NullThrowsReasons.MissingToken(
'type keyword',
'import specifier',
),
);
fixes.push(
fixer.removeRange([
qualifier.range[0],
specifier.imported.range[0],
]),
);
}
const importKeyword = util.nullThrows(
sourceCode.getFirstToken(node, util.isImportKeyword),
util.NullThrowsReasons.MissingToken('import keyword', 'import'),
);
fixes.push(fixer.insertTextAfter(importKeyword, ' type'));
return fixes;
},
});
},
};
},
});