Skip to content

Commit faa2766

Browse files
committed
fix: get the most alike package dir and exclude current app dir
1 parent 1eb8236 commit faa2766

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

.vscode/settings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"json.format.enable": false,
1111
// Required to allow auto format on save with Prettier + ESLint + Vetur.
1212
"editor.codeActionsOnSave": {
13-
"source.fixAll.eslint": true
13+
"source.fixAll.eslint": "explicit"
1414
},
1515
"eslint.alwaysShowStatus": true,
1616
"sort-imports.suppress-warnings": true,

src/index.ts

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { isAbsolute, join, resolve } from 'path';
1+
import { isAbsolute, join, resolve, sep } from 'path';
22
import { existsSync, lstatSync } from 'fs';
33
import type { CompilerOptions } from 'typescript';
44
import type { Package } from '@manypkg/get-packages';
@@ -63,6 +63,36 @@ function getTsConfigMapping(packages: Package[]) {
6363
return result;
6464
}
6565

66+
function getMatchedIndex(sourcePath: string, targetPath: string) {
67+
const sourcePathArray = sourcePath.split(sep);
68+
const targetPathArray = targetPath.split(sep);
69+
let matchedIndex = -1;
70+
71+
for (let i = 0; i < Math.min(sourcePathArray.length, targetPathArray.length); i++) {
72+
if (sourcePathArray[i] === targetPathArray[i]) {
73+
matchedIndex = Math.max(i, matchedIndex);
74+
}
75+
}
76+
77+
return matchedIndex;
78+
}
79+
80+
function getExactMatchedPackage(packages: Package[], importer: string): Package | null {
81+
let matchedIndex = -1;
82+
let result = null;
83+
84+
packages.forEach((pkg) => {
85+
const matchedIndexForPackage = getMatchedIndex(importer, pkg.dir);
86+
87+
if (matchedIndexForPackage > matchedIndex && importer.includes(pkg.dir)) {
88+
matchedIndex = matchedIndexForPackage;
89+
result = pkg;
90+
}
91+
});
92+
93+
return result;
94+
}
95+
6696
const defaultOptions = {
6797
alias: {},
6898
ignorePackages: undefined,
@@ -130,7 +160,7 @@ export default async function tsMonoAlias(options: TsMonoAliasOption = defaultOp
130160
}
131161

132162
const resolvedImporter = resolve(importer);
133-
const importedFromPackage = packages.find((pkg) => resolvedImporter.includes(pkg.dir));
163+
const importedFromPackage = getExactMatchedPackage(packages, resolvedImporter);
134164

135165
if (!importedFromPackage) {
136166
return null;

0 commit comments

Comments
 (0)