Skip to content

Commit f486492

Browse files
authored
fix: False-positive no-extraneous-import when using the tsconfig > paths alias import (#408)
1 parent 5544f20 commit f486492

File tree

5 files changed

+45
-0
lines changed

5 files changed

+45
-0
lines changed

lib/util/import-target.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,20 @@ module.exports = class ImportTarget {
176176
return "node"
177177
}
178178

179+
// This check should be done before the RegExp that checks npm packages,
180+
// because `tsconfig.json` aliases may start with `~`, `@` and this will
181+
// cause imports using aliases to be treated as npm-module imports
182+
// https://github.com/eslint-community/eslint-plugin-n/issues/379
183+
if (isTypescript(this.context)) {
184+
const aliases = getTSConfigAliases(this.context)
185+
if (
186+
Array.isArray(aliases) &&
187+
aliases.some(alias => this.name.startsWith(alias.name))
188+
) {
189+
return "relative"
190+
}
191+
}
192+
179193
if (/^(@[\w~-][\w.~-]*\/)?[\w~-][\w.~-]*/.test(this.name)) {
180194
return "npm"
181195
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
// File needs to exists
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export default {};
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"compilerOptions": {
3+
"paths": {
4+
"~configurations/*": ["./src/configurations/*"],
5+
"@configurations/*": ["./src/configurations/*"],
6+
"#configurations/*": ["./src/configurations/*"]
7+
}
8+
}
9+
}

tests/lib/rules/no-extraneous-import.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ function fixture(name) {
3333

3434
const ruleTester = new RuleTester({
3535
languageOptions: { sourceType: "module" },
36+
settings: {
37+
n: {
38+
tryExtensions: [".ts"],
39+
},
40+
},
3641
})
3742
ruleTester.run("no-extraneous-import", rule, {
3843
valid: [
@@ -78,6 +83,21 @@ ruleTester.run("no-extraneous-import", rule, {
7883
filename: fixture("dependencies/a.js"),
7984
code: "import ccc from 'ccc'",
8085
},
86+
87+
// imports using `tsconfig.json > compilerOptions > paths` setting
88+
// https://github.com/eslint-community/eslint-plugin-n/issues/379
89+
{
90+
filename: fixture("tsconfig-paths/index.ts"),
91+
code: "import foo from '@configurations/foo'",
92+
},
93+
{
94+
filename: fixture("tsconfig-paths/index.ts"),
95+
code: "import foo from '~configurations/foo'",
96+
},
97+
{
98+
filename: fixture("tsconfig-paths/index.ts"),
99+
code: "import foo from '#configurations/foo'",
100+
},
81101
],
82102
invalid: [
83103
{

0 commit comments

Comments
 (0)