Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(resolveAlias): handle aliases ending with trailing slash #155

Merged
merged 8 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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