Skip to content

Commit

Permalink
fix(resolveAlias): handle aliases ending with trailing slash (#155)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pooya@pi0.io>
  • Loading branch information
huang-julien and pi0 committed Jan 10, 2024
1 parent dffa918 commit 2fa8aaa
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
19 changes: 16 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,16 @@ export function normalizeAliases(_aliases: Record<string, string>) {
export function resolveAlias(path: string, aliases: Record<string, string>) {
const _path = normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
for (const alias in aliases) {
if (_path.startsWith(alias) && pathSeparators.has(_path[alias.length])) {
return join(aliases[alias], _path.slice(alias.length));
for (const [alias, to] of Object.entries(aliases)) {
if (!_path.startsWith(alias)) {
continue;
}

// Strip trailing slash from alias for check
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;

if (hasTrailingSlash(_path[_alias.length])) {
return join(to, _path.slice(alias.length));
}
}
return _path;
Expand All @@ -61,3 +68,9 @@ export function filename(path: string) {
function _compareAliases(a: string, b: string) {
return b.split("/").length - a.split("/").length;
}

// Returns true if path ends with a slash or **is empty**
function hasTrailingSlash(path = "/") {
const lastChar = path[path.length - 1];
return lastChar === "/" || lastChar === "\\";
}
12 changes: 12 additions & 0 deletions test/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ describe("alias", () => {
"@": "/root",
bingpot: "@/bingpot/index.ts",
test: "@bingpot/index.ts",
"~": "/root/index.js",
"~/": "/src",
"~win": "C:/root/index.js",
"~win/": "C:/src",
};
const aliases = normalizeAliases(_aliases);

Expand All @@ -20,6 +24,10 @@ describe("alias", () => {
"@foo/bar/utils": "@foo/bar/dist/utils.mjs",
"bingpot": "/root/bingpot/index.ts",
"test": "@bingpot/index.ts",
"~": "/root/index.js",
"~/": "/src",
"~win": "C:/root/index.js",
"~win/": "C:/src",
}
`);
});
Expand All @@ -43,6 +51,10 @@ describe("alias", () => {
expect(resolveAlias("foo/bar.js", aliases)).toBe("foo/bar.js");
expect(resolveAlias("./bar.js", aliases)).toBe("./bar.js");
});
it("respect ending with /", () => {
expect(resolveAlias("~/foo/bar", aliases)).toBe("/src/foo/bar");
expect(resolveAlias("~win/foo/bar", aliases)).toBe("C:/src/foo/bar");
});
});
});

Expand Down

0 comments on commit 2fa8aaa

Please sign in to comment.