Skip to content

Commit a16d286

Browse files
Hint at tsconfig path aliases when void.config.ts fails to load (#801)
Closes #800. `void.config.ts` is loaded with jiti, which only aliases `void/config`, so an import through tsconfig `paths` failed with an error that reads like a missing package. `env.ts` already detects this case and adds a hint; the config loader now does the same. ## Changes - Moved `extractFailedSpecifier()` and `looksLikeAlias()` from `host/load-user-env.ts` into a new `host/alias-hint.ts`, with an `aliasHint(err, file)` helper that both loaders use. - `extractFailedSpecifier()` now also accepts `MODULE_NOT_FOUND`, the code jiti's `require`-based loading reports. - `loadVoidConfig()` appends the hint when the failed specifier looks like an alias: ``` config: Could not load void.config.ts: Cannot find module '@/lib/theme' Require stack: - /path/to/app/void.config.ts Hint: '@/lib/theme' looks like a tsconfig path alias. void.config.ts does not resolve tsconfig "paths" — use a relative import (e.g. "./shared/...") instead. ``` - `docs/reference/config.md` now says to use relative imports or package names in `void.config.ts`, matching the `env.ts` note in the env vars guide. The `env.ts` hint wording changes slightly ("env.ts does not resolve tsconfig "paths"" instead of "env.ts is loaded directly by Node and does not resolve…") so both files share one message. ## Tests - New `packages/void/test/unit/config-loader.test.ts`: a relative import loads, an `@/…` import gets the hint, and a missing scoped package (`@scope/pkg`) doesn't. - `vp test run` (full suite: 793 files, 16674 tests passed) and `vp run check` pass. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent a2eecec commit a16d286

5 files changed

Lines changed: 133 additions & 50 deletions

File tree

‎docs/reference/config.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ export default defineConfig({
4444

4545
TypeScript provides editor completion and checks. Void validates the config again when it runs, including values computed at runtime.
4646

47+
Use relative imports or package names inside `void.config.ts`. TypeScript path aliases such as `@/lib/theme` are not supported.
48+
4749
The shorter JSON fragments below show individual fields to place inside `defineConfig({ ... })`.
4850

4951
## Fields

‎packages/void/src/config-loader.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from 'node:fs';
22
import { fileURLToPath } from 'node:url';
33
import { createJiti } from 'jiti';
44
import { join } from 'pathslash';
5+
import { aliasHint } from './host/alias-hint.ts';
56

67
export const LEGACY_CONFIG_FILE = 'void.json';
78
export const TYPED_CONFIG_FILE = 'void.config.ts';
@@ -51,10 +52,9 @@ export function loadVoidConfig(root: string): LoadedVoidConfig | null {
5152
try {
5253
return { source: TYPED_CONFIG_FILE, value: loadTypedVoidConfigFile(typedPath) };
5354
} catch (error) {
54-
throw new Error(
55-
`config: Could not load ${TYPED_CONFIG_FILE}: ${error instanceof Error ? error.message : String(error)}`,
56-
{ cause: error },
57-
);
55+
const base = `config: Could not load ${TYPED_CONFIG_FILE}: ${error instanceof Error ? error.message : String(error)}`;
56+
const hint = aliasHint(error, TYPED_CONFIG_FILE);
57+
throw new Error(hint ? `${base}\n\n${hint}` : base, { cause: error });
5858
}
5959
}
6060

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* Detects tsconfig path aliases in module-resolution errors from files that
3+
* Void loads outside Vite (`env.ts` through Node's `import()`, `void.config.ts`
4+
* through jiti), neither of which resolves tsconfig `paths`.
5+
*
6+
* Node-only (lives under `host/`). Must not be imported from anything
7+
* that ships in worker bundles.
8+
*/
9+
10+
/** Returns the failed specifier from a Node or jiti module-resolution error, or `null`. */
11+
export function extractFailedSpecifier(err: unknown): string | null {
12+
if (!(err instanceof Error)) {
13+
return null;
14+
}
15+
// `import()` reports `ERR_MODULE_NOT_FOUND`; jiti loads through `require`,
16+
// which reports `MODULE_NOT_FOUND`.
17+
const code = (err as NodeJS.ErrnoException).code;
18+
if (
19+
code !== 'ERR_MODULE_NOT_FOUND' &&
20+
code !== 'MODULE_NOT_FOUND' &&
21+
code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED'
22+
) {
23+
return null;
24+
}
25+
// Node's message shapes: `Cannot find package '@/foo' imported from ...`
26+
// or `Cannot find module '@/foo' imported from ...`.
27+
const match = /Cannot find (?:package|module) '([^']+)'/.exec(err.message);
28+
return match ? (match[1] ?? null) : null;
29+
}
30+
31+
/** A specifier is alias-shaped if it isn't relative, absolute, a node: URL, or a valid bare package name. */
32+
export function looksLikeAlias(specifier: string): boolean {
33+
if (
34+
specifier.startsWith('./') ||
35+
specifier.startsWith('../') ||
36+
specifier.startsWith('/') ||
37+
specifier.startsWith('node:') ||
38+
specifier.startsWith('file:')
39+
) {
40+
return false;
41+
}
42+
// Bare scoped package: `@scope/name[/subpath]` where scope and name are valid.
43+
// Alias forms like `@/foo` fail this because the scope is empty.
44+
if (specifier.startsWith('@')) {
45+
return !/^@[^/]+\/[^/]+/.test(specifier);
46+
}
47+
// Tilde and plain `#` prefixes are common alias conventions that aren't
48+
// valid bare packages.
49+
return specifier.startsWith('~') || specifier.startsWith('#');
50+
}
51+
52+
/** The alias hint for a failed load of `file`, or `null` when the error isn't an alias import. */
53+
export function aliasHint(err: unknown, file: string): string | null {
54+
const specifier = extractFailedSpecifier(err);
55+
if (!specifier || !looksLikeAlias(specifier)) {
56+
return null;
57+
}
58+
return (
59+
`Hint: '${specifier}' looks like a tsconfig path alias. ` +
60+
`${file} does not resolve tsconfig "paths" — ` +
61+
`use a relative import (e.g. "./shared/...") instead.`
62+
);
63+
}

‎packages/void/src/host/load-user-env.ts‎

Lines changed: 3 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -15,62 +15,19 @@
1515
* that ships in worker bundles.
1616
*/
1717
import { pathToFileURL } from 'node:url';
18+
import { aliasHint } from './alias-hint.ts';
1819

1920
let loadCounter = 0;
2021

21-
/** Returns the failed specifier from a Node module-resolution error, or `null`. */
22-
function extractFailedSpecifier(err: unknown): string | null {
23-
if (!(err instanceof Error)) {
24-
return null;
25-
}
26-
const code = (err as NodeJS.ErrnoException).code;
27-
if (code !== 'ERR_MODULE_NOT_FOUND' && code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
28-
return null;
29-
}
30-
// Node's message shapes: `Cannot find package '@/foo' imported from ...`
31-
// or `Cannot find module '@/foo' imported from ...`.
32-
const match = /Cannot find (?:package|module) '([^']+)'/.exec(err.message);
33-
return match ? (match[1] ?? null) : null;
34-
}
35-
36-
/** A specifier is alias-shaped if it isn't relative, absolute, a node: URL, or a valid bare package name. */
37-
function looksLikeAlias(specifier: string): boolean {
38-
if (
39-
specifier.startsWith('./') ||
40-
specifier.startsWith('../') ||
41-
specifier.startsWith('/') ||
42-
specifier.startsWith('node:') ||
43-
specifier.startsWith('file:')
44-
) {
45-
return false;
46-
}
47-
// Bare scoped package: `@scope/name[/subpath]` where scope and name are valid.
48-
// Alias forms like `@/foo` fail this because the scope is empty.
49-
if (specifier.startsWith('@')) {
50-
return !/^@[^/]+\/[^/]+/.test(specifier);
51-
}
52-
// Tilde and plain `#` prefixes are common alias conventions that aren't
53-
// valid bare packages.
54-
return specifier.startsWith('~') || specifier.startsWith('#');
55-
}
56-
5722
export async function loadUserEnvFile(envFile: string): Promise<void> {
5823
// Counter + timestamp so back-to-back HMR reloads in the same millisecond
5924
// still produce distinct URLs (Node's ESM loader caches by URL).
6025
const url = pathToFileURL(envFile).href + `?t=${Date.now()}-${++loadCounter}`;
6126
try {
6227
await import(/* @vite-ignore */ url);
6328
} catch (err) {
64-
const specifier = extractFailedSpecifier(err);
6529
const base = `env: Failed to load '${envFile}': '${(err as Error).message}'.`;
66-
if (specifier && looksLikeAlias(specifier)) {
67-
throw new Error(
68-
`${base}\n\n` +
69-
`Hint: '${specifier}' looks like a tsconfig path alias. ` +
70-
`env.ts is loaded directly by Node and does not resolve tsconfig "paths" — ` +
71-
`use a relative import (e.g. "./shared/...") instead.`,
72-
);
73-
}
74-
throw new Error(base);
30+
const hint = aliasHint(err, 'env.ts');
31+
throw new Error(hint ? `${base}\n\n${hint}` : base);
7532
}
7633
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2+
import { tmpdir } from 'node:os';
3+
import { join } from 'node:path';
4+
import { afterEach, describe, expect, it } from 'vite-plus/test';
5+
import { loadVoidConfig } from '../../src/config-loader.ts';
6+
7+
/**
8+
* Coverage for the void.config.ts loader. jiti only aliases `void/config`,
9+
* so tsconfig path aliases fail to resolve — they get detected and produce
10+
* the same hint as env.ts.
11+
*/
12+
13+
const roots: Array<string> = [];
14+
15+
function createTempProject(config: string): string {
16+
const root = mkdtempSync(join(tmpdir(), 'void-config-loader-'));
17+
roots.push(root);
18+
writeFileSync(join(root, 'void.config.ts'), config);
19+
return root;
20+
}
21+
22+
afterEach(() => {
23+
for (const root of roots.splice(0, roots.length)) {
24+
rmSync(root, { recursive: true, force: true });
25+
}
26+
});
27+
28+
describe('loadVoidConfig', () => {
29+
it('loads void.config.ts with relative imports', () => {
30+
const root = createTempProject(
31+
'import { defineConfig } from "void/config";\n' +
32+
'import { SOURCE_DIR } from "./shared.ts";\n' +
33+
'export default defineConfig({ sourceDir: SOURCE_DIR });\n',
34+
);
35+
writeFileSync(join(root, 'shared.ts'), 'export const SOURCE_DIR = "src";\n');
36+
37+
expect(loadVoidConfig(root)).toEqual({
38+
source: 'void.config.ts',
39+
value: { sourceDir: 'src' },
40+
});
41+
});
42+
43+
it('gives a targeted hint when void.config.ts imports through a tsconfig path alias', () => {
44+
const root = createTempProject(
45+
'import { defineConfig } from "void/config";\n' +
46+
'import { SOURCE_DIR } from "@/lib/shared";\n' +
47+
'export default defineConfig({ sourceDir: SOURCE_DIR });\n',
48+
);
49+
50+
expect(() => loadVoidConfig(root)).toThrow(
51+
/Could not load void\.config\.ts.*Hint: '@\/lib\/shared' looks like a tsconfig path alias.*use a relative import/s,
52+
);
53+
});
54+
55+
it('does not add the alias hint for a genuine missing bare package', () => {
56+
const root = createTempProject('import "@definitely-not-installed/pkg";\nexport default {};\n');
57+
58+
expect(() => loadVoidConfig(root)).toThrow(/Could not load void\.config\.ts/);
59+
expect(() => loadVoidConfig(root)).not.toThrow(/tsconfig path alias/);
60+
});
61+
});

0 commit comments

Comments
 (0)