Skip to content

Commit

Permalink
refactor: handle 1 remaining default import
Browse files Browse the repository at this point in the history
  • Loading branch information
mshanemc committed Dec 13, 2023
1 parent 058b380 commit f790043
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/rules/esm-message-import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
/* eslint-disable complexity */
import { RuleCreator } from '@typescript-eslint/utils/eslint-utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import { ASTUtils, AST_NODE_TYPES } from '@typescript-eslint/utils';

export const esmMessageImport = RuleCreator.withoutDocs({
meta: {
Expand Down Expand Up @@ -74,18 +74,29 @@ export const esmMessageImport = RuleCreator.withoutDocs({
} else {
// case 2, just remove the 1 unused specifier
if (node.specifiers.length > 1) {
const replacementSpecifiers = node.specifiers
.filter((s) => s.local.name !== 'dirname' && s.local.name !== 'fileURLToPath')
.map((s) => context.sourceCode.getText(s))
.join(', ');
const replacementSpecifiers = node.specifiers.filter(
(s) => s.local.name !== 'dirname' && s.local.name !== 'fileURLToPath'
);
const replacementText = replacementSpecifiers.map((s) => context.sourceCode.getText(s)).join(', ');

const replacementRange = [
node.specifiers[0].range[0],
node.specifiers[node.specifiers.length - 1].range[1],
// +
// (replacementSpecifiers.every(ASTUtils.isNodeOfType(AST_NODE_TYPES.ImportDefaultSpecifier))
// ? 0
// : 1)
] as const;
return context.report({
node,
messageId: 'unnecessaryImport',
fix: (fixer) => fixer.replaceTextRange(replacementRange, replacementSpecifiers),
fix: (fixer) =>
replacementSpecifiers.every(ASTUtils.isNodeOfType(AST_NODE_TYPES.ImportDefaultSpecifier))
? fixer.replaceText(
node,
`import ${replacementSpecifiers[0].local.name} from '${node.source.value}'`
)
: fixer.replaceTextRange(replacementRange, replacementText),
});
}
}
Expand Down
17 changes: 17 additions & 0 deletions test/rules/esm-message-imports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,23 @@ Messages.importMessagesDirectoryFromMetaUrl(import.meta.url)
output: `
import { resolve as pathResolve, join } from 'node:path'
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url)
`,
},
{
name: 'default import outside of destructured',
errors: [
{
messageId: 'unnecessaryImport',
},
],
code: `
import path, { dirname } from 'node:path'
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url)
`,
// other code (ex: prettier) can handle the extra whitespaces
output: `
import path from 'node:path'
Messages.importMessagesDirectoryFromMetaUrl(import.meta.url)
`,
},
],
Expand Down

0 comments on commit f790043

Please sign in to comment.