Skip to content

Commit b547335

Browse files
mohitk05camc314
andauthored
fix(linter/import-first): correctly respect all relative path imports (#17268)
Closes: #17020 Update path pattern check for `is_relative_import` in `import/first` import rule and add supporting tests. Co-authored-by: Cameron <[email protected]>
1 parent 4ac23e1 commit b547335

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

crates/oxc_linter/src/rules/import/first.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,9 @@ declare_oxc_lint!(
8383
);
8484

8585
fn is_relative_path(path: &str) -> bool {
86-
path.starts_with("./")
86+
// A path is considered relative if it starts with "/", "./", or "../"
87+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#module_specifier_resolution
88+
path.starts_with("./") || path.starts_with("../") || path.starts_with('/')
8789
}
8890

8991
/// <https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/first.md>
@@ -169,6 +171,17 @@ fn test() {
169171
export { x, y }",
170172
None,
171173
),
174+
// Relative imports with absolute-first
175+
(
176+
r"import { y } from 'bar';
177+
import { x } from '../foo';",
178+
Some(json!(["absolute-first"])),
179+
),
180+
(
181+
r"import { y } from 'bar';
182+
import { x } from '/foo';",
183+
Some(json!(["absolute-first"])),
184+
),
172185
];
173186

174187
let fail = vec![
@@ -208,6 +221,17 @@ fn test() {
208221
import F3 = require('mod');",
209222
None,
210223
),
224+
// Relative imports with absolute-first
225+
(
226+
r"import { x } from '../foo';
227+
import { y } from 'bar';",
228+
Some(json!(["absolute-first"])),
229+
),
230+
(
231+
r"import { x } from '/foo';
232+
import { y } from 'bar';",
233+
Some(json!(["absolute-first"])),
234+
),
211235
];
212236

213237
Tester::new(First::NAME, First::PLUGIN, pass, fail)

crates/oxc_linter/src/snapshots/import_first.snap

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,19 @@ source: crates/oxc_linter/src/tester.rs
8181
· ───────────────────────────
8282
╰────
8383
help: Move import statement to the top of the file
84+
85+
eslint-plugin-import(first): Relative imports before absolute imports are prohibited
86+
╭─[index.ts:2:33]
87+
1import { x } from '../foo';
88+
2import { y } from 'bar';
89+
· ─────
90+
╰────
91+
help: Move absolute import above relative import
92+
93+
eslint-plugin-import(first): Relative imports before absolute imports are prohibited
94+
╭─[index.ts:2:33]
95+
1import { x } from '/foo';
96+
2import { y } from 'bar';
97+
· ─────
98+
╰────
99+
help: Move absolute import above relative import

0 commit comments

Comments
 (0)