Skip to content

Commit

Permalink
fix: False-positive no-extraneous-import when using the `tsconfig >…
Browse files Browse the repository at this point in the history
… paths` alias import (#408)
  • Loading branch information
MorevM authored Feb 23, 2025
1 parent 5544f20 commit f486492
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/util/import-target.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,20 @@ module.exports = class ImportTarget {
return "node"
}

// This check should be done before the RegExp that checks npm packages,
// because `tsconfig.json` aliases may start with `~`, `@` and this will
// cause imports using aliases to be treated as npm-module imports
// https://github.com/eslint-community/eslint-plugin-n/issues/379
if (isTypescript(this.context)) {
const aliases = getTSConfigAliases(this.context)
if (
Array.isArray(aliases) &&
aliases.some(alias => this.name.startsWith(alias.name))
) {
return "relative"
}
}

if (/^(@[\w~-][\w.~-]*\/)?[\w~-][\w.~-]*/.test(this.name)) {
return "npm"
}
Expand Down
1 change: 1 addition & 0 deletions tests/fixtures/no-extraneous/tsconfig-paths/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// File needs to exists
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default {};
9 changes: 9 additions & 0 deletions tests/fixtures/no-extraneous/tsconfig-paths/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"compilerOptions": {
"paths": {
"~configurations/*": ["./src/configurations/*"],
"@configurations/*": ["./src/configurations/*"],
"#configurations/*": ["./src/configurations/*"]
}
}
}
20 changes: 20 additions & 0 deletions tests/lib/rules/no-extraneous-import.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ function fixture(name) {

const ruleTester = new RuleTester({
languageOptions: { sourceType: "module" },
settings: {
n: {
tryExtensions: [".ts"],
},
},
})
ruleTester.run("no-extraneous-import", rule, {
valid: [
Expand Down Expand Up @@ -78,6 +83,21 @@ ruleTester.run("no-extraneous-import", rule, {
filename: fixture("dependencies/a.js"),
code: "import ccc from 'ccc'",
},

// imports using `tsconfig.json > compilerOptions > paths` setting
// https://github.com/eslint-community/eslint-plugin-n/issues/379
{
filename: fixture("tsconfig-paths/index.ts"),
code: "import foo from '@configurations/foo'",
},
{
filename: fixture("tsconfig-paths/index.ts"),
code: "import foo from '~configurations/foo'",
},
{
filename: fixture("tsconfig-paths/index.ts"),
code: "import foo from '#configurations/foo'",
},
],
invalid: [
{
Expand Down

0 comments on commit f486492

Please sign in to comment.