Skip to content

Commit

Permalink
fix: shortest import should prefer alias with ~ at the start
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
SimeonC committed Nov 1, 2023
1 parent 912df07 commit 1d1ba82
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
4 changes: 4 additions & 0 deletions packages/eslint-plugin/__tests__/shortestImport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
16 changes: 12 additions & 4 deletions packages/eslint-plugin/src/shortestImport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down

0 comments on commit 1d1ba82

Please sign in to comment.