Skip to content

Commit 51df70f

Browse files
committed
fix: handle external deps with tsconfig baseUrl
1 parent f932c0c commit 51df70f

File tree

5 files changed

+46
-6
lines changed

5 files changed

+46
-6
lines changed

.env

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
TEST=value

lib/__fixtures__/dotenv-test/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import 'dotenv/config';
2+
3+
console.log(process.env.TEST)
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"compilerOptions": {
3+
"baseUrl": "."
4+
}
5+
}

lib/createSourceFileTree.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from "node:fs";
2+
import { createRequire } from "node:module";
23
import fsPath from "node:path";
3-
import { fileURLToPath } from "node:url";
4+
import { fileURLToPath, pathToFileURL } from "node:url";
45

56
import { Expression, Literal, Program } from "acorn";
67
import { simple } from "acorn-walk";
@@ -167,11 +168,23 @@ const createSourceFileTreeRecursive = ({
167168
}
168169
}
169170
if (firstError) {
170-
throw new XnrError(
171-
`Could not find import:\n ${prettyPath(rawImport.importPath)}\nfrom:\n ${prettyPath(
172-
absResolvedPath
173-
)}`
174-
);
171+
// This can be reached is an npm dependency is also a valid local path
172+
// e.g. when tsconfig has baseUrl set
173+
// So we only error if it is not a resolvable npm dependency
174+
try {
175+
let { importPath } = rawImport;
176+
if (importPath.startsWith("file://")) {
177+
importPath = fileURLToPath(importPath);
178+
}
179+
createRequire(pathToFileURL(absResolvedPath)).resolve(importPath);
180+
return [];
181+
} catch {
182+
throw new XnrError(
183+
`Could not find import:\n ${prettyPath(rawImport.importPath)}\nfrom:\n ${prettyPath(
184+
absResolvedPath
185+
)}`
186+
);
187+
}
175188
}
176189
throw new Error("Unreachable");
177190
});

lib/run.test.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,24 @@ test("run a file directly (success with stdout)", async () => {
118118
expect(stderr).toBe("");
119119
});
120120

121+
test("run a file directly (dotenv)", async () => {
122+
let stdout = "";
123+
let stderr = "";
124+
await expect(
125+
run({
126+
filePath: "lib/__fixtures__/dotenv-test/index.ts",
127+
onWriteStdout: (out) => {
128+
stdout += out;
129+
},
130+
onWriteStderr: (err) => {
131+
stderr += err;
132+
},
133+
})
134+
).resolves.toBe(0);
135+
expect(stdout).toBe("value\n");
136+
expect(stderr).toBe("");
137+
});
138+
121139
test("run a file directly (ansi escape)", async () => {
122140
let stdout = "";
123141
let stderr = "";

0 commit comments

Comments
 (0)