Skip to content

Commit e07eedd

Browse files
authored
fix(init): write ESM config files in CommonJS packages (#970)
In a package with `"type": "commonjs"`, which `npm init -y` writes, the React, Vue, Svelte and Solid starters from `void init` fail in dev, build and preview: ``` Error: Failed to resolve "@void/svelte/plugin". This package is ESM only but it was tried to load by `require`. ``` In these packages, the starters now use `vite.config.mts`, and all four work. An inferred env schema goes to `env.mts` there, because `void env check` can't load `env.ts` (`Cannot use import statement outside a module`). When `sourceDir` is set, the inferred schema now goes there, where Void reads it, instead of to a root file Void ignores. The warning from #176 to add `"type": "module"` is removed, because it only showed after the Vite config had loaded as ESM, and those builds work.
1 parent 136a527 commit e07eedd

10 files changed

Lines changed: 180 additions & 80 deletions

File tree

‎docs/guide/env-vars.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ Declare your environment variables in `env.ts`, then read them through `env` fro
1010

1111
Create `env.ts` at the project root:
1212

13+
For a package with `"type": "commonjs"` in `package.json`, use `env.mts`.
14+
1315
```ts
1416
import { defineEnv, number, string, url } from 'void/env';
1517

‎docs/reference/cli/setup.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ void init [--tsconfig] [--github] [--git | --no-git]
3333
[--toolchain <name>] [--framework <name>] [--starter <name>] [--deploy <target>]
3434
```
3535

36-
Set up a new or existing Void project. In an empty directory, choose Vite+ or Vite, a framework, and a D1, PostgreSQL, MySQL, or Static Pages starter. The new app's `void.config.ts` turns on [`routing.typedRoutes`](../config.md#routing-typedroutes).
36+
Set up a new or existing Void project. In an empty directory, choose Vite+ or Vite, a framework, and a D1, PostgreSQL, MySQL, or Static Pages starter. For a package with `"type": "commonjs"`, starters use `vite.config.mts` and inferred env schemas use `env.mts`. The new app's `void.config.ts` turns on [`routing.typedRoutes`](../config.md#routing-typedroutes).
3737

3838
Pass your choices as flags to scaffold from a script or coding agent:
3939

‎packages/void/src/cli/env-scaffold.ts‎

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
/**
2-
* `void init` hook — when the project has no `env.ts` but has dotenv files
3-
* on disk, scaffold an `env.ts` whose keys mirror what the user already
4-
* has. Inference is intentionally permissive: we only upgrade from the
5-
* default `string()` helper when the value is unambiguously a boolean,
2+
* During `void init`, scaffold an environment schema for the keys in a
3+
* project's existing `.env`. Use the default `string()` helper unless the value is a boolean,
64
* URL, or small integer. Everything else stays a string and carries a
75
* one-line banner nudging the user to tighten the schema.
86
*
97
* This is a best-effort DX sweetener, not a correctness boundary — a
108
* wrong guess only costs the user a single-line edit.
119
*/
12-
import { existsSync, writeFileSync } from 'node:fs';
13-
import { join } from 'pathslash';
10+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
11+
import { basename, join } from 'pathslash';
12+
import { readProjectPaths } from '../project-paths.ts';
1413
import { parseDotenvFile } from '../shared/dotenv.ts';
14+
import { readPackageJson } from '../shared/package-json.ts';
1515

1616
export type InferredHelper = 'string' | 'number' | 'boolean' | 'url';
1717

@@ -61,7 +61,7 @@ export function collectInferredEntries(root: string): Array<InferredEntry> {
6161
}
6262

6363
/**
64-
* Render the scaffolded `env.ts` body. The imports are pulled in lazily
64+
* Render the scaffolded schema. The imports are pulled in lazily
6565
* so only helpers we reference appear in the import statement.
6666
*/
6767
export function renderEnvTs(entries: Array<InferredEntry>): string {
@@ -108,26 +108,27 @@ export type ScaffoldResult = {
108108
};
109109

110110
/**
111-
* If the project has no `env.ts`, scaffold one based on the local `.env`
112-
* user already has. Safe to call unconditionally during `void init` — it
113-
* no-ops when `env.ts` is present. Never overwrites an existing file.
111+
* Scaffold a schema from `.env` when the project does not already have one.
114112
*/
115113
export function maybeScaffoldEnvTs(root: string): ScaffoldResult {
116-
// Respect `env.*` at the root or under `src/`, whichever the user already uses.
117-
for (const dir of ['', 'src/']) {
118-
for (const ext of ['ts', 'mts', 'js', 'mjs']) {
119-
if (existsSync(join(root, `${dir}env.${ext}`))) {
120-
return { written: null, skipReason: 'env-ts-exists', entries: [] };
121-
}
122-
}
114+
const commonJs = readPackageJson(root)?.type === 'commonjs';
115+
const { sourceDir, sourceRoot, envFileCandidates } = readProjectPaths(root);
116+
const hasSchema = envFileCandidates.some(
117+
(file) => existsSync(file) || (sourceDir !== '' && existsSync(join(root, basename(file)))),
118+
);
119+
if (hasSchema) {
120+
return { written: null, skipReason: 'env-ts-exists', entries: [] };
123121
}
124122

125123
if (!existsSync(join(root, '.env'))) {
126124
return { written: null, skipReason: 'no-dotenv-files', entries: [] };
127125
}
128126

129127
const entries = collectInferredEntries(root);
130-
const target = join(root, 'env.ts');
128+
const target = join(sourceRoot, commonJs ? 'env.mts' : 'env.ts');
129+
if (sourceDir) {
130+
mkdirSync(sourceRoot, { recursive: true });
131+
}
131132
writeFileSync(target, renderEnvTs(entries));
132133
return { written: target, entries };
133134
}

‎packages/void/src/cli/init.ts‎

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ import type { DeploymentPlatform } from './project.ts';
5555
import {
5656
createPagesStarterTemplate,
5757
detectScaffoldFrameworkFromDependencies,
58+
getGeneratedViteConfigPath,
5859
getScaffoldTsconfigCompilerOptions,
5960
SCAFFOLD_BASE_DEV_DEPENDENCIES,
6061
SCAFFOLD_FRAMEWORKS,
@@ -2022,17 +2023,6 @@ function scaffoldPagesApp(
20222023
): boolean {
20232024
const packageJsonPath = join(root, 'package.json');
20242025
const packageJsonExisted = existsSync(packageJsonPath);
2025-
const template = createPagesStarterTemplate({
2026-
framework,
2027-
starterMode,
2028-
toolchain,
2029-
voidPackageSpec: resolveScaffoldDependencySpec(root, 'void', getOwnVersion()),
2030-
adapterPackageSpec: resolveScaffoldDependencySpec(
2031-
root,
2032-
SCAFFOLD_FRAMEWORKS[framework].adapterPackage,
2033-
getOwnVersion(),
2034-
),
2035-
});
20362026
let pkg: JsonObject = {};
20372027

20382028
if (packageJsonExisted) {
@@ -2054,6 +2044,19 @@ function scaffoldPagesApp(
20542044
pkg.type = 'module';
20552045
}
20562046

2047+
const template = createPagesStarterTemplate({
2048+
framework,
2049+
starterMode,
2050+
toolchain,
2051+
packageType: pkg.type,
2052+
voidPackageSpec: resolveScaffoldDependencySpec(root, 'void', getOwnVersion()),
2053+
adapterPackageSpec: resolveScaffoldDependencySpec(
2054+
root,
2055+
SCAFFOLD_FRAMEWORKS[framework].adapterPackage,
2056+
getOwnVersion(),
2057+
),
2058+
});
2059+
20572060
const scripts = asRecord(pkg.scripts) ?? {};
20582061
pkg.scripts = scripts;
20592062
for (const [name, command] of Object.entries(template.scripts)) {
@@ -2259,11 +2262,6 @@ export default defineConfig({
22592262
`;
22602263
}
22612264

2262-
function getGeneratedViteConfigPath(root: string): 'vite.config.ts' | 'vite.config.mts' {
2263-
const pkg = readPackageJson(root);
2264-
return pkg?.type === 'module' ? 'vite.config.ts' : 'vite.config.mts';
2265-
}
2266-
22672265
function noteManualViteConfigSetup(configPath?: string): void {
22682266
const target = configPath ?? 'your framework Vite config';
22692267
note(
@@ -2352,7 +2350,13 @@ function ensureExistingProjectViteConfig(
23522350

23532351
const configPath = findViteConfig(root);
23542352
if (!configPath) {
2355-
writeFileIfMissing(root, getGeneratedViteConfigPath(root), getBasicVoidViteConfig(), report);
2353+
const packageType = readPackageJson(root)?.type;
2354+
writeFileIfMissing(
2355+
root,
2356+
getGeneratedViteConfigPath(packageType),
2357+
getBasicVoidViteConfig(),
2358+
report,
2359+
);
23562360
return;
23572361
}
23582362

‎packages/void/src/cli/template.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,17 +181,25 @@ export function getScaffoldTsconfigCompilerOptions(
181181
return framework ? { ...SCAFFOLD_FRAMEWORKS[framework].tsconfigCompilerOptions } : {};
182182
}
183183

184+
export function getGeneratedViteConfigPath(
185+
packageType: unknown,
186+
): 'vite.config.ts' | 'vite.config.mts' {
187+
return packageType === 'module' ? 'vite.config.ts' : 'vite.config.mts';
188+
}
189+
184190
export function createPagesStarterTemplate(options: {
185191
framework: ScaffoldFramework;
186192
starterMode: ScaffoldStarterMode;
187193
toolchain?: ScaffoldToolchain;
194+
packageType?: unknown;
188195
voidPackageSpec: string;
189196
adapterPackageSpec: string;
190197
}): PagesStarterTemplate {
191198
const {
192199
framework,
193200
starterMode,
194201
toolchain = 'vite',
202+
packageType = 'module',
195203
voidPackageSpec,
196204
adapterPackageSpec,
197205
} = options;
@@ -203,7 +211,7 @@ export function createPagesStarterTemplate(options: {
203211
{ routing: { typedRoutes: true } },
204212
'// Generated by void init.',
205213
),
206-
'vite.config.ts': getViteConfig(framework, config, toolchain),
214+
[getGeneratedViteConfigPath(packageType)]: getViteConfig(framework, config, toolchain),
207215
[`pages/index.${config.pageExtension}`]: getIndexPage(framework, starterMode),
208216
'pages/style.css': starterStyles,
209217
'pages/vite-env.d.ts': '/// <reference types="vite/client" />\n',

‎packages/void/src/index.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ import { cloudflare } from './plugin-cloudflare.ts';
4141
import type { WorkerConfig, AuxiliaryWorkerConfig } from './plugin-cloudflare.ts';
4242
import {
4343
afterServerReady,
44-
warnIfPackageJsonIsNotEsm,
4544
isViteBuildOrPreview,
4645
getOrCreateDevTriggerToken,
4746
devTriggerSecretGuardPlugin,
@@ -108,7 +107,6 @@ export function voidPlugin(options?: {
108107
// needs it, because build prerendering can open a remote session too.
109108
selectVoidCloudflareLogin();
110109
}
111-
warnIfPackageJsonIsNotEsm(root);
112110
// Token only matters in serve — the dispatch module that uses it is
113111
// DCE'd from production worker bundles. In build/preview we still need
114112
// *some* string (the wrapper embeds it for completeness), but we skip

‎packages/void/src/plugin-dev-config.ts‎

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import {
22
chmodSync,
33
closeSync,
4-
existsSync,
54
mkdirSync,
65
openSync,
76
readFileSync,
@@ -10,7 +9,6 @@ import {
109
} from 'node:fs';
1110
import { join } from 'pathslash';
1211
import type { Plugin, PluginOption, ViteDevServer } from 'vite';
13-
import { voidWarn } from './log.ts';
1412

1513
/**
1614
* Whether Vite is resolving the server that Vitest creates to run tests, whatever its `--mode`.
@@ -215,37 +213,3 @@ export function devTriggerSecretGuardPlugin(): Plugin {
215213
},
216214
};
217215
}
218-
219-
/**
220-
* Warn when the project's `package.json` does not declare `"type": "module"`.
221-
*
222-
* Vite's default `configLoader: "bundle"` bundles `vite.config.ts`,
223-
* externalizes deps, and then loads the bundle. When `package.json` is non-ESM
224-
* the bundle is written as `.js` and loaded via CJS `require()`, which throws
225-
* `ERR_REQUIRE_ASYNC_MODULE` if any externalized dep's ESM graph contains
226-
* top-level await. `@cloudflare/vite-plugin` (which voidPlugin pulls in) has
227-
* exactly such a TLA, so non-ESM consumers hit this on every Vite invocation.
228-
*
229-
* Runs once per Vite process (factory time), single sync read.
230-
*/
231-
export function warnIfPackageJsonIsNotEsm(root: string): void {
232-
const pkgPath = join(root, 'package.json');
233-
if (!existsSync(pkgPath)) {
234-
return;
235-
}
236-
let pkg: { type?: unknown };
237-
try {
238-
pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { type?: unknown };
239-
} catch {
240-
return;
241-
}
242-
if (pkg.type === 'module') {
243-
return;
244-
}
245-
voidWarn(
246-
'package.json is missing `"type": "module"`. Vite\'s default config loader ' +
247-
'will fail with ERR_REQUIRE_ASYNC_MODULE on transitive top-level await ' +
248-
'(e.g. @cloudflare/vite-plugin). Add `"type": "module"` to package.json, ' +
249-
'or run vite build with `--configLoader runner`.',
250-
);
251-
}

‎packages/void/test/integration/prepare-cli.test.ts‎

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
import { spawnSync } from 'node:child_process';
2-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2+
import {
3+
existsSync,
4+
mkdirSync,
5+
mkdtempSync,
6+
readFileSync,
7+
rmSync,
8+
symlinkSync,
9+
writeFileSync,
10+
} from 'node:fs';
311
import { tmpdir } from 'node:os';
412
import { join } from 'node:path';
513
import { pathToFileURL } from 'node:url';
@@ -45,10 +53,12 @@ function createProject(options: { withSources?: boolean; sourceDir?: string } =
4553
function runVoid(
4654
root: string,
4755
args: Array<string>,
56+
input?: string,
4857
): { stdout: string; stderr: string; status: number } {
4958
const res = spawnSync(process.execPath, [CLI_ENTRY, ...args], {
5059
cwd: root,
5160
encoding: 'utf8',
61+
input,
5262
env: {
5363
PATH: process.env.PATH,
5464
HOME: root,
@@ -69,6 +79,67 @@ afterEach(() => {
6979
}
7080
});
7181

82+
it.each([
83+
['commonjs', 'env.mts'],
84+
['module', 'env.ts'],
85+
])('builds a %s app with a sourceDir env schema after init', (type, schemaFile) => {
86+
const root = createProject();
87+
const vite = join(PACKAGE_ROOT, 'node_modules', 'vite');
88+
mkdirSync(join(root, 'node_modules'));
89+
symlinkSync(PACKAGE_ROOT, join(root, 'node_modules', 'void'), 'junction');
90+
symlinkSync(vite, join(root, 'node_modules', 'vite'), 'junction');
91+
writeFileSync(
92+
join(root, 'package.json'),
93+
JSON.stringify({
94+
name: 'source-dir-app',
95+
type,
96+
devDependencies: { typescript: '*', vite: '*', void: '*' },
97+
}),
98+
);
99+
writeFileSync(join(root, 'void.config.ts'), "export default { sourceDir: 'app' };\n");
100+
writeFileSync(
101+
join(root, type === 'commonjs' ? 'vite.config.mts' : 'vite.config.ts'),
102+
"import { voidPlugin } from 'void';\nexport default { plugins: [voidPlugin()] };\n",
103+
);
104+
writeFileSync(join(root, 'index.html'), '<!doctype html><main>Source directory app</main>\n');
105+
writeFileSync(join(root, '.env'), 'TEST_GREETING=hello\n');
106+
mkdirSync(join(root, 'app', 'routes'), { recursive: true });
107+
writeFileSync(
108+
join(root, 'app', 'routes', 'hello.ts'),
109+
"export const GET = () => new Response('ok');\n",
110+
);
111+
const envFile = join(root, 'app', schemaFile);
112+
const schema =
113+
"import { defineEnv, string } from 'void/env';\nexport default defineEnv({ TEST_GREETING: string() });\n";
114+
if (type === 'commonjs') {
115+
writeFileSync(envFile, schema);
116+
}
117+
118+
// Select "No Database Yet" for this existing project.
119+
const init = runVoid(root, ['init', '--deploy', 'none', '--no-git'], '\u001b[B'.repeat(3) + '\r');
120+
expect(init.status, init.stdout + init.stderr).toBe(0);
121+
const envTypes = join(root, '.void', 'env.d.ts');
122+
rmSync(envTypes, { force: true });
123+
const buildSource = `import { createBuilder } from 'vite';
124+
const builder = await createBuilder({});
125+
await builder.buildApp();`;
126+
const build = spawnSync(process.execPath, ['--input-type=module', '--eval', buildSource], {
127+
cwd: root,
128+
encoding: 'utf8',
129+
timeout: 30_000,
130+
});
131+
expect(build.status, build.stderr).toBe(0);
132+
const schemaSource = readFileSync(envFile, 'utf8');
133+
if (type === 'commonjs') {
134+
expect(schemaSource).toBe(schema);
135+
} else {
136+
expect(schemaSource).toContain('TEST_GREETING: string(),');
137+
}
138+
expect(readFileSync(envTypes, 'utf8')).toContain(`typeof import("../app/${schemaFile}")`);
139+
expect(existsSync(join(root, 'env.ts'))).toBe(false);
140+
expect(existsSync(join(root, 'env.mts'))).toBe(false);
141+
});
142+
72143
describe('void prepare (subprocess)', () => {
73144
it('generates custom binding types and removes them when switching targets', () => {
74145
const root = createProject();

0 commit comments

Comments
 (0)