diff --git a/packages/basic/index.js b/packages/basic/index.js index 5cdef79..042bde3 100644 --- a/packages/basic/index.js +++ b/packages/basic/index.js @@ -293,5 +293,6 @@ module.exports = { // antfu 'antfu/no-leading-newline': 'error', 'antfu/if-newline': 'error', + 'antfu/prefer-inline-type-import': 'error', }, } diff --git a/packages/eslint-plugin-antfu/src/index.ts b/packages/eslint-plugin-antfu/src/index.ts index b713057..05db2be 100644 --- a/packages/eslint-plugin-antfu/src/index.ts +++ b/packages/eslint-plugin-antfu/src/index.ts @@ -1,9 +1,11 @@ import ifNewline from './rules/if-newline' import noLeadingNewline from './rules/no-leading-newline' +import preferInlineTypeImport from './rules/prefer-inline-type-import' export default { rules: { 'no-leading-newline': noLeadingNewline, 'if-newline': ifNewline, + 'prefer-inline-type-import': preferInlineTypeImport, }, } diff --git a/packages/eslint-plugin-antfu/src/rules/prefer-inline-type-import.ts b/packages/eslint-plugin-antfu/src/rules/prefer-inline-type-import.ts new file mode 100644 index 0000000..34f076d --- /dev/null +++ b/packages/eslint-plugin-antfu/src/rules/prefer-inline-type-import.ts @@ -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({ + 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, + ]) + } +}