Repository navigation
fix(core): let package.json "type" decide .ts format under node* modules - #908
Conversation
(oxc-project#907) Under `node16`, `node18` and `nodenext`, `tsc` emits each `.ts` file in the format its `package.json` `"type"` gives it. The resolve hook reported every `.ts` and `.tsx` file as an ES module under those settings instead, so a CommonJS file that Node.js loads through the module hooks (the entry point, a test file, or a file an ES module imports) ran without `require` or `module` and failed with "require is not defined in ES module scope", in `"type": "commonjs"` packages and in packages without a `"type"` alike. Only an ES `module` setting (`es6`, `es2015` to `esnext`) now makes a `.ts` or `.tsx` file an ES module; otherwise the package decides, as it already did for `node20`. A file with `import`/`export` still runs as an ES module: the load hook finds its module syntax, as it does without a tsconfig. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Add `node20` to the node* test list and a test for `import x = require()` plus `export =` in a "type": "commonjs" package under nodenext. Name issue oxc-project#907 on the describe block, and reword the `default_module_from_tsconfig` comment so it only describes the resolve format: the load hook still switches a file with module syntax to ESM. Refs oxc-project#907. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Brooooooklyn
left a comment
There was a problem hiding this comment.
Thanks! Verified against tsc emit and plain Node; all CI green.
…CommonJS (#910) AI generated, but ran the fix against a dummy repo locally. Fixes #909 ## Summary Type erasure removes `import type` and the other type-only declarations whole, so Node.js' type stripping runs a file whose only module syntax is type-only as CommonJS. oxc-node ran it as an ES module, without `require`, `module` or `exports`. | file (`"type": "commonjs"` unless noted) | before | after | | --- | --- | --- | | `import type` + `require`: entry point, `require()`d, or imported from `.mts` | ESM: `require is not defined in ES module scope` | CommonJS | | `export type { … }` (± `from`), `export type *`, `export type X =`, `export interface`, `export default interface`, `export declare …` | ESM | CommonJS | | the same in a package without `"type"` | ESM: `ReferenceError` | CommonJS | | `import type` + `export =` | `TS(1203)` | CommonJS | | `import { type X }`, a value export, `import.meta`, top-level await, `export {}`, or a `let`/`const`/`class` named `require`/`module`/`exports`/`__filename`/`__dirname` | ESM | ESM (unchanged) | | `.mts`, or `.ts` in a `"type": "module"` package, loaded any way | ESM | ESM (unchanged) | ## Fix - `parsed_as_esm` and `has_module_declaration` skip declarations that type erasure removes whole (`is_type_only_module_declaration`). `import { type X } from "x"` still counts: it leaves `import {} from "x"`, which is module syntax to Node.js. - `oxc_transform` compiles such a file the way a `.cts` file is compiled: no trailing `export {}`, helpers are `require()`d. This applies only to `.ts`/`.tsx`/`.js`/`.jsx` and extensionless files outside a `"type": "module"` package, and not when the file's tsconfig sets an ES `module` (the resolve hook reports those as ES modules). The importer ignores the tsconfig `module`, as it always has, so there the switch stays. - A file that redeclares a CommonJS wrapper name with `let`/`const`/`class` stays ESM, as Node.js' syntax detection does. - `import type X = require()` is erased too, and an alias such as `import C = N.C` is a plain binding: neither holds the file to CommonJS the way `import x = require()` does, so top-level await beside them still makes the file an ES module. - The public `transform()` output for such a file no longer ends in `export {};`. `@oxc-node/core/importer` changes the same way. ## On the #759 test This replaces #759's `a file whose only module syntax is a type-only import runs as an ES module`. That held while the output kept the injected `export {}`. Compiled as a `.cts` file is, nothing module-like is left, so the CommonJS path runs it and it gets `require`, `module` and `exports`, as under Node.js and tsc. The no-crash intent of #759 is still checked: every test asserts exit code 0. ## Tests | test | main | this PR | | --- | --- | --- | | every type-only form, commonjs package: entry / `.mts` import / `require()` | fail | pass | | package without `"type"` | fail | pass | | `import type` + `export =`, `require()`d | fail | pass | | 8 guards (inline `type`, value export, `import.meta`, TLA, enum, class, function, namespace with a value) | pass | pass | | `require()` of a type-only `.mts`, and of a `.ts` in a module package, stays ESM | pass | pass | | `transform()` output: `import type` drops `export {}`; `import { type X }` and `.mts` keep it | fail (1 row) | pass | | redeclared wrapper name: 3 rows stay ESM, `var exports` stays CommonJS | pass (3 rows), fail (`var exports`) | pass | | `require()` + `import()` of a type-only `.ts` under tsconfig `module: esnext` runs once, as ESM | pass | pass | | `import type X = require()`: alone CommonJS, beside top-level await ESM | pass | pass | | importer, tsconfig `module: esnext`: type-only file with a legacy decorator runs as CommonJS | pass | pass | | `import C = N.C` alias: beside top-level await ESM, beside `require` CommonJS | pass | pass | | `helper-imports.spec.ts`: commonjs `entry.ts` with a type-only import | fail | pass | | `helper-imports.spec.ts`: 2 module rows | pass | pass | ## Verification Node.js v26.13.0, darwin-arm64, branch merged with current main (#908 included): `vp run test` (633 passed, 7 skipped), `cargo test --all-features`, `cargo clippy --all-targets --all-features -- -D warnings`, `cargo fmt --check`, `vp fmt --check` and `vp lint` all pass. Against the first commit of this PR, the `require()` of type-only ESM tests, the `.mts` `transform()` row, 3 of the redeclaration rows, the `module: esnext` test, the `import type =` + await row and the importer test and the alias + await row fail at the commit before each fix; they cover six bugs Codex found in review. ## Not covered - A named import from an ES module (`import { x } from "./file.ts"`) of such a file still fails with `does not provide an export named`, as on main (and for `.cts`): `cjs-module-lexer` reads the raw `.ts`, where the `import type` line stops it. Default imports and `require()` work. - A namespace that holds only types (`export namespace N { export type T = number }`) still counts as module syntax, although Node.js strips it. Same as main. - `require()` of a `.ts` file with no module syntax in a `"type": "module"` package runs as CommonJS. Same as main. --------- Co-authored-by: DArcy Rush <[email protected]> Co-authored-by: LongYinan <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
… (#911) #908 and #910 are merged; this branch is up to date with `main`. AI generated, but ran the fix against a full live CJS project. The project uses `package.json` type as `commonjs` with all file extensions as `.ts` running NestJS 12 (ESM) and tests mocked using nodes test module `mock.method`. I needed to upgrade to TypeScript 7.0.2 from 5.9.3 which ts-node doesn't support. tsx and other don't support legacy TypeScript decorators (or rather `emitDecoratorMetadata`, which NestJS uses). I'm not aware of any other JIT that supports CJS projects needing emit decorator metadata on TS7+. Closes #905 ### Problem In a `"type": "commonjs"` package, a `.ts` file that uses `import`/`export` runs as an ES module under oxc-node, even when tsconfig compiles it to CommonJS. Its namespace object is then frozen, so `mock.method()` from `node:test` can't replace its exports. Under `tsc` it can. ``` package.json "type": "commonjs", tsconfig "module": "node20" test.ts: import * as lib from "../src/lib"; mock.method(lib, "compute", …) main this PR tsc oxnode --test TypeError: Cannot redefine property pass pass ``` Node.js' own type stripping doesn't run this file as an ES module either: it rejects it with `SyntaxError: Cannot use import statement outside a module`. ### Fix A file with ES module syntax is compiled to CommonJS the way `tsc` compiles it when all of these hold: - its package is `"type": "commonjs"` - its tsconfig `module` is `commonjs`, `node16`, `node18`, `node20` or `nodenext` (any case) - its extension is ambiguous: `.ts`, `.tsx`, `.js`, `.jsx` or none - it uses neither `import.meta` nor top-level await, which have no CommonJS form - it declares none of the names the CommonJS wrapper or the helpers below use: `exports`, `require`, `module`, `__filename`, `__dirname`, `__importDefault`, `__importStar`, `__exportStar` Anywhere else, such as a package with no `"type"`, `"type": "module"`, or an ES `module` setting, the file runs as an ES module, as before. Switching a project's `"type"` to `"module"` turns the compilation off. The output has `tsc`'s shape. It's built from the module runner transform's output: - An export of a local that is never reassigned is a plain data property (`exports.a = void 0; … exports.a = a;`). It's writable, so `mock.method(namespace, "a")` reaches every importer. A hoisted function is exported up front. - A reassigned local, a decorated class and a namespace are `exports.a` itself, as `tsc` emits them: live, writable, and `undefined` (not a TDZ error) when an import cycle reads them early. Re-exports stay live through getters, in the form `cjs-module-lexer` detects, defined after their `require()`. A reassigned local exported under two names, declared by destructuring or set to an anonymous function also gets a getter. - An anonymous default function is hoisted as `default_1` and exported up front. A side-effect import is a bare `require()`. - A named import is `require()`'s result. Default and namespace imports go through `__importDefault`/`__importStar`, `export *` through `__exportStar`, and `import()` stays `import()`. - On the load-hook path the compiled source is returned with `format: "commonjs"`, so an ES module importer gets the named exports. The compiled code `require()`s `./lib.js` where the source imported `./lib.js`. So `Module._resolveFilename` in `register.mjs` falls back to the TypeScript source (`.js` → `.ts`/`.tsx`, `.jsx` → `.tsx`/`.ts`, `.mjs` → `.mts`, `.cjs` → `.cts`). When the output is missing, `./x.js` also finds `x.jsx` and `./x.jsx` finds `x.js`. For a TypeScript importer outside `node_modules`, it also prefers the source over compiled output sitting beside it, as the ES module resolver does since #840, and `config.ts` over `config.json` for `./config`; a file inside `node_modules` keeps its compiled `.js`. A bare request tries tsconfig `paths` and `baseUrl` first, through the new `tsconfigPathCandidates` binding. The hook thread's helper tag is registered on the main thread too, so the compiled files can `require()` their helpers. Under `node16`, `node18` and `nodenext`, the resolve hook no longer reports every `.ts` file as an ES module; the package's `"type"` decides, as it does for `tsc`. #908 made that change and is merged. ### Behaviour changes These apply only to projects with `"type": "commonjs"` and one of the `module` settings above: - A file with `import`/`export` now runs as CommonJS. An ES module's default import of it is `module.exports`, with the file's default export at `.default`, the same as TypeScript types it under `nodenext`. - An ES module importer doesn't see names the file re-exports with `export *` from another TypeScript file: Node.js only follows re-exports into `.js` and `.cjs` files. - Under `node16`/`node18`/`nodenext`, a `.ts` file without module syntax is CommonJS, also when an ES module imports it. - An ES module importer's named imports are a snapshot taken when the file finishes loading, as for any CommonJS module. - The compiled file's dependencies resolve with the `require` condition, as under `tsc`; a package whose `exports` offers only `import` fails. - Node.js caches a relative `require()` per directory and request, so when a `.js` file and a `.ts` file in one directory both `require("./lib.js")` next to `lib.ts`, whichever asks first decides which file both get. - `require()` of an ES module from a compiled file loaded through the module hooks needs nodejs/node#59679 (22.22.3 on the 22.x line). Earlier versions fail with `TypeError: Cannot read properties of undefined (reading 'exports')`. The README has a new "ES module syntax in a CommonJS package" section covering this. ### Tests - Rust: `commonjs_lowering` covers each `module` setting, the output shape (reassigned exports, side-effect imports, the anonymous default function), the cases that stay ES modules (`import.meta`, reserved names, `esnext`, `preserve`, `.mts`, a package without `"type"`), and type-only or `declare`d reserved names that still compile. - New `packages/integrate-commonjs` package (`"type": "commonjs"`, `module: nodenext`, run with `oxnode --test`), 20 tests: - mocking a namespace export, a function and a class, with importers seeing the mock - live reassigned exports - default, star and CommonJS imports - `.js` names finding `.ts`, with the source preferred over compiled output beside it - an ES module importer's named and default imports - import cycles: hoisted functions, and `undefined` for a reassigned `let`, a decorated class, a namespace and a re-export read early - a namespace import of a CommonJS class keeping its static members - a tsconfig `paths` alias and the `.js` → `.jsx` fallback - stack trace lines - `import.meta` and top-level await staying ES modules - runtime helpers - `commonjs.test.ts` fails to load on `main`. `helpers.test.ts` passes on both and guards what must not change. - `commonjs-lowering.spec.ts` (vitest) covers `paths` and `baseUrl`, `config.ts` beside `config.json`, the `.js`/`.jsx` fallbacks, `node_modules` files and non-enumerable exports. - The #905 repro passes on Node.js 26.12.1 and 22.22.1. `vp run test` (643 vitest tests plus the three `node --test` packages), `cargo test`, clippy and fmt pass. --------- Co-authored-by: DArcy Rush <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: LongYinan <[email protected]>
AI generated, but ran the fix against a dummy repo locally.
Fixes #907
Summary
Under
module: node16,node18andnodenext,tscemits each.tsfile in the format itspackage.json"type"gives it, and a package without"type"is CommonJS. oxc-node's resolve hookreported every
.tsand.tsxfile as an ES module under those settings instead. So TypeScriptwritten as CommonJS failed in
"type": "commonjs"packages and in packages without a"type":"type": "commonjs",module: nodenextunless noted)require/module.exports(alsonode16,node18)require is not defined in ES module scopeimport x = require()/export =TS(1202): Import assignment cannot be used when targeting ECMAScript modules.tsfile imported from an.mtsfileReferenceErrornode:testfile usingimport x = require(), run with--testTS(1202)"type",require/module.exportsReferenceErrormodule: node20import/export,import.meta, top-levelawait)module: es6,es2015…esnextFix
default_module_from_tsconfigno longer groupsnode16,node18andnodenextwith the ES modulesettings. Only an ES
modulesetting (es6,es2015,es2020,es2022,esnext) makes a.tsor.tsxfile an ES module. Under any other setting the package's"type"decides, as it already didfor
node20.A file with module syntax still runs as an ES module: the resolve hook now reports it as CommonJS,
and the load hook finds its syntax and switches it to ESM, as it does without a tsconfig.
Tests
New
describeblock inresolved-format.spec.ts(issue #907):node16,node18,node20,nodenext: a.tsentry point, and a.tsxfile imported from an.mtsfile, in a"type": "commonjs"package run as CommonJS.nodenext: a.tsfile without module syntax in a package without"type"runs as CommonJS.nodenext:import x = require()plusexport =in a"type": "commonjs"package runs as CommonJS..tsfile withexportin a package without"type"still runs as an ES module;module: esnextstill makes a.tsfile an ES module.With the
src/lib.rschange reverted, five tests fail;node20and the two guards pass either way.Verification
cargo test --all-featurespass;cargo fmt,cargo clippy -D warnings,vp fmt --checkandvp lintare clean.tsc's output, on oxc-node frommain, and on this branch. Everycase that changed now matches
tsc; no case moved away from it.Not in scope
"type": "commonjs"package still runs as an ES module, wheretscwouldcompile it to CommonJS (Clarify module resolution with .ts files using import and package.json type commonjs #905).
import type/export type/export interfacestill runs as anES module, because type-only declarations count as module syntax.
module: esnext, a file without module syntax still runs as an ES module, althoughtscemitsit as a script.
.tsxfile with no imports in a non-"type": "module"package now runs as CommonJS, liketsc,so a
jsxImportSourcethat only resolves through tsconfigpathsno longer resolves(CommonJS
requiredoes not usepaths).