Skip to content

Commit

Permalink
Fix the path separators returned by resolveImport
Browse files Browse the repository at this point in the history
  • Loading branch information
illright committed Jun 30, 2024
1 parent 6418817 commit d7ff317
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
25 changes: 15 additions & 10 deletions src/resolve-import.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { sep } from "node:path";
import ts from "typescript";
import type { CompilerOptions } from "typescript";

/**
* Given a file name, an imported path, and a TSConfig object, produce a path to the imported file, relative to TypeScript's `baseUrl`.
*
* The resulting path uses OS-appropriate path separators.
*
* @example
* ```tsx
* // ./src/pages/home/ui/HomePage.tsx
Expand Down Expand Up @@ -41,16 +44,18 @@ export function resolveImport(
directoryExists?: (path: string) => boolean,
): string | null {
return (
ts.resolveModuleName(
importedPath,
importerPath,
normalizeCompilerOptions(tsCompilerOptions),
{
...ts.sys,
fileExists,
directoryExists,
},
).resolvedModule?.resolvedFileName ?? null
ts
.resolveModuleName(
importedPath,
importerPath,
normalizeCompilerOptions(tsCompilerOptions),
{
...ts.sys,
fileExists,
directoryExists,
},
)
.resolvedModule?.resolvedFileName?.replaceAll("/", sep) ?? null
);
}

Expand Down
7 changes: 4 additions & 3 deletions src/specs/resolve-import.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { expect, test } from "vitest";
import { resolveImport } from "../index.js";
import { join } from "node:path";

test("Basic", () => {
const tsCompilerOptions = {
Expand All @@ -21,7 +22,7 @@ test("Basic", () => {
tsCompilerOptions,
fileExists,
),
).toBe("src/shared/ui/index.ts");
).toBe(join("src", "shared", "ui", "index.ts"));
});

test("With deprecated moduleResolution: node", () => {
Expand All @@ -44,7 +45,7 @@ test("With deprecated moduleResolution: node", () => {
tsCompilerOptions,
fileExists,
),
).toBe("src/shared/ui/index.ts");
).toBe(join("src", "shared", "ui", "index.ts"));
});

test("Alias to absolute paths (for whatever reason)", () => {
Expand All @@ -65,5 +66,5 @@ test("Alias to absolute paths (for whatever reason)", () => {
tsCompilerOptions,
fileExists,
),
).toBe("/src/shared/ui/Button.ts");
).toBe(join("/", "src", "shared", "ui", "Button.ts"));
});

0 comments on commit d7ff317

Please sign in to comment.