feat: add prefer-inline-type-import

This commit is contained in:
Anthony Fu 2022-04-07 05:53:45 +08:00
parent eaff018580
commit d23abea648
3 changed files with 63 additions and 0 deletions

View File

@ -293,5 +293,6 @@ module.exports = {
// antfu // antfu
'antfu/no-leading-newline': 'error', 'antfu/no-leading-newline': 'error',
'antfu/if-newline': 'error', 'antfu/if-newline': 'error',
'antfu/prefer-inline-type-import': 'error',
}, },
} }

View File

@ -1,9 +1,11 @@
import ifNewline from './rules/if-newline' import ifNewline from './rules/if-newline'
import noLeadingNewline from './rules/no-leading-newline' import noLeadingNewline from './rules/no-leading-newline'
import preferInlineTypeImport from './rules/prefer-inline-type-import'
export default { export default {
rules: { rules: {
'no-leading-newline': noLeadingNewline, 'no-leading-newline': noLeadingNewline,
'if-newline': ifNewline, 'if-newline': ifNewline,
'prefer-inline-type-import': preferInlineTypeImport,
}, },
} }

View File

@ -0,0 +1,60 @@
// Ported from https://github.com/gajus/eslint-plugin-canonical/blob/master/src/rules/preferInlineTypeImport.js
// by Gajus Kuizinas https://github.com/gajus
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) => {
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, sourceCode, node) {
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,
])
}
}