Skip to content

Commit 4189085

Browse files
committed
fix(test-utils): Support both CJS and ESM for __dirname
Use import.meta.url in ESM environments and __dirname in CJS. This fixes the ReferenceError when tests run as ES modules.
1 parent ee9ae35 commit 4189085

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

dev-packages/test-utils/src/spotlight.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,20 @@ import { spawn } from 'child_process';
55
import * as fs from 'fs';
66
import * as path from 'path';
77
import * as readline from 'readline';
8+
import { fileURLToPath } from 'url';
9+
10+
/**
11+
* Get the directory name, works in both CJS and ESM environments.
12+
*/
13+
function getDirname(): string {
14+
// ESM environment
15+
if (typeof import.meta !== 'undefined' && import.meta.url) {
16+
return path.dirname(fileURLToPath(import.meta.url));
17+
}
18+
// CJS environment
19+
// eslint-disable-next-line no-restricted-globals
20+
return __dirname;
21+
}
822

923
/**
1024
* Find the monorepo root by looking for a package.json with workspaces.
@@ -30,7 +44,7 @@ function findRepoRoot(startDir: string): string {
3044
}
3145

3246
// Find spotlight binary in repo root's node_modules
33-
const REPO_ROOT = findRepoRoot(__dirname);
47+
const REPO_ROOT = findRepoRoot(getDirname());
3448
const SPOTLIGHT_BIN = path.join(REPO_ROOT, 'node_modules', '.bin', 'spotlight');
3549

3650
interface SpotlightOptions {

0 commit comments

Comments
 (0)