fix: CJS detection regression for packages with "export" in comments (#3793)

Closes https://github.com/denoland/fresh/issues/3794

Fixes a regression from #3767 where CJS npm packages fail with `exports
is not defined` in dev mode.

- The old heuristic (`code.includes("export ")`) was fooled by the word
"export" appearing in comments of CJS files — e.g. `@opentelemetry/api`
has `// TODO: Remove ProxyTracerProvider export in the next major
version.` which caused the CJS shim to be skipped entirely
- Replaces the naive string check with two-layer detection:
1. **Package.json `type` field** (Node.js semantics): `.cjs` → always
CJS, `.js` → CJS unless nearest `package.json` has `"type": "module"`.
Results cached per directory.
2. **ESM statement regex fallback**: for dual CJS/ESM packages that ship
ESM in `.js` without `"type": "module"` (e.g. `@opentelemetry/api`,
`preact-render-to-string`), detects actual ESM syntax including minified
forms like `import{` and `export*from`
- Adds a test importing from a real CJS npm package (`qs`) in
`node_modules` — the existing "CJS test" fixtures were local ESM files
that never exercised the shim path
This commit is contained in:
Bartek Iwańczuk
2026-04-28 09:02:44 +02:00
committed by GitHub
parent 71e849cfcf
commit 838f41abc5
3 changed files with 90 additions and 35 deletions
@@ -452,6 +452,17 @@ Deno.test({
sanitizeResources: false,
});
Deno.test({
name: "vite dev - CJS npm package (qs)",
fn: async () => {
const res = await fetch(`${demoServer.address()}/tests/cjs_npm`);
const text = await res.text();
expect(text).toContain("<h1>qs-ok</h1>");
},
sanitizeOps: false,
sanitizeResources: false,
});
// issue: https://github.com/denoland/fresh/issues/3666
integrationTest(
"vite dev - basePath does not intercept Vite URLs",