Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 24 additions & 7 deletions src/rules/extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,19 +355,27 @@ export default createRule<Options, MessageId>({
)
const extensionForbidden = isUseOfExtensionForbidden(extension)
if (extensionRequired && !extensionForbidden) {
const fixedImportPath = stringifyPath({
pathname: `${
const pathname =
extension &&
`${
/([\\/]|[\\/]?\.?\.)$/.test(importPath)
? `${
importPath.endsWith('/')
? importPath.slice(0, -1)
: importPath
}/index.${extension}`
: `${importPath}.${extension}`
}`,
query,
hash,
})
}`
const fixedImportPath =
extension && stringifyPath({ pathname, query, hash })

if (
importPath === fixedImportPath ||
resolvedPath !== resolve(pathname, context)
) {
return
}

const fixOrSuggest = {
fix(fixer: TSESLint.RuleFixer) {
return fixer.replaceText(
Expand All @@ -376,6 +384,7 @@ export default createRule<Options, MessageId>({
)
},
}

context.report({
node: source,
messageId: extension ? 'missingKnown' : 'missing',
Expand Down Expand Up @@ -408,11 +417,17 @@ export default createRule<Options, MessageId>({
) {
const fixedPathname = importPath.slice(0, -(extension.length + 1))
const isIndex = fixedPathname.endsWith('/index')
const pathname = isIndex ? fixedPathname.slice(0, -6) : fixedPathname
const fixedImportPath = stringifyPath({
pathname: isIndex ? fixedPathname.slice(0, -6) : fixedPathname,
pathname,
query,
hash,
})

if (resolvedPath !== resolve(pathname, context)) {
return
}

const fixOrSuggest = {
fix(fixer: TSESLint.RuleFixer) {
return fixer.replaceText(
Expand All @@ -421,6 +436,7 @@ export default createRule<Options, MessageId>({
)
},
}

const commonSuggestion = {
...fixOrSuggest,
messageId: 'removeUnexpected' as const,
Expand All @@ -430,6 +446,7 @@ export default createRule<Options, MessageId>({
fixedImportPath,
},
}

context.report({
node: source,
messageId: 'unexpected',
Expand Down
5 changes: 5 additions & 0 deletions test/rules/extensions.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,11 @@ ruleTester.run('extensions', rule, {
code: "import foo from './foo.js';",
options: [{ fix: true, pattern: { js: 'always' } }],
}),

tValid({
code: "import eslint from 'eslint';",
options: [{ fix: true, pattern: { js: 'always' } }],
}),
],

invalid: [
Expand Down
Loading