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
@@ -0,0 +1,6 @@
import qs from "qs";
export default function Page() {
const parsed = qs.parse("a=1&b=2");
return <h1>{parsed.a === "1" ? "qs-ok" : "qs-fail"}</h1>;
}