/
prefer-inline-type-import.ts
64 lines (57 loc) · 1.98 KB
/
prefer-inline-type-import.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
// Ported from https://github.com/gajus/eslint-plugin-canonical/blob/master/src/rules/preferInlineTypeImport.js
// by Gajus Kuizinas https://github.com/gajus
import type { TSESTree } from '@typescript-eslint/utils'
import type { RuleFixer, SourceCode } from '@typescript-eslint/utils/dist/ts-eslint'
import { createEslintRule } from '../utils'
export const RULE_NAME = 'prefer-inline-type-import'
export type MessageIds = 'preferInlineTypeImport'
export type Options = []
export default createEslintRule<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description: 'Newline after if',
recommended: 'error',
},
fixable: 'code',
schema: [],
messages: {
preferInlineTypeImport: 'Prefer inline type import',
},
},
defaultOptions: [],
create: (context) => {
const sourceCode = context.getSourceCode()
return {
ImportDeclaration: (node) => {
// ignore bare type imports
if (node.specifiers.length === 1 && ['ImportNamespaceSpecifier', 'ImportDefaultSpecifier'].includes(node.specifiers[0].type))
return
if (node.importKind === 'type') {
context.report({
*fix(fixer) {
yield * removeTypeSpecifier(fixer, sourceCode, node)
for (const specifier of node.specifiers)
yield fixer.insertTextBefore(specifier, 'type ')
},
loc: node.loc,
messageId: 'preferInlineTypeImport',
node,
})
}
},
}
},
})
function * removeTypeSpecifier(fixer: RuleFixer, sourceCode: Readonly<SourceCode>, node: TSESTree.ImportDeclaration) {
const importKeyword = sourceCode.getFirstToken(node)
const typeIdentifier = sourceCode.getTokenAfter(importKeyword)
yield fixer.remove(typeIdentifier)
if (importKeyword.loc.end.column + 1 === typeIdentifier.loc.start.column) {
yield fixer.removeRange([
importKeyword.range[1],
importKeyword.range[1] + 1,
])
}
}