From 1d1ba8287e6fd4740beed292533623e7a2ca4c14 Mon Sep 17 00:00:00 2001 From: SimeonC <1085899+SimeonC@users.noreply.github.com> Date: Wed, 1 Nov 2023 18:02:15 +0900 Subject: [PATCH] fix: shortest import should prefer alias with `~` at the start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolves the following scenario; * `../Common/ShopSelect` * `~/Common/ShopSelect` These are considered “same length” but we want to prefer the `~` alias path as it’s easier to read than the relative path. --- .../__tests__/shortestImport.test.ts | 4 ++++ packages/eslint-plugin/src/shortestImport.ts | 16 ++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/eslint-plugin/__tests__/shortestImport.test.ts b/packages/eslint-plugin/__tests__/shortestImport.test.ts index 96335c52..3807ca67 100644 --- a/packages/eslint-plugin/__tests__/shortestImport.test.ts +++ b/packages/eslint-plugin/__tests__/shortestImport.test.ts @@ -172,6 +172,10 @@ typescriptSetups.forEach((config) => { path: '~/feature2/index', filename: './test_src/feature1/slice1/index.ts', }, + { + path: '~/feature2/index', + filename: './test_src/feature1/index.ts', + }, { path: '~/feature1/index', filename: './test_src/feature1/slice1/index.ts', diff --git a/packages/eslint-plugin/src/shortestImport.ts b/packages/eslint-plugin/src/shortestImport.ts index 73a87573..7d0ff849 100644 --- a/packages/eslint-plugin/src/shortestImport.ts +++ b/packages/eslint-plugin/src/shortestImport.ts @@ -291,10 +291,18 @@ class RuleChecker { return avoidRelativeParents.includes(relativeRoot); }); const allPathsWithLength = (aliasPaths.length ? aliasPaths : baseUrlPaths) - .map((aliasPath) => ({ - aliasPath, - length: aliasPath.split('/').length, - })) + .map((aliasPath) => { + const parts = aliasPath.split('/'); + if (parts[0].match(/^[^a-z0-9]$/i)) + return { + aliasPath, + length: parts.length - 1, + }; + return { + aliasPath, + length: parts.length, + }; + }) .sort((a, b) => a.length - b.length); const shortestAliasPath = allPathsWithLength[0];