Skip to content

fix(core): let package.json "type" decide .ts format under node* modules - #908

Merged
Brooooooklyn merged 2 commits into
oxc-project:mainfrom
darcyrush:fix/nodenext-commonjs-format
Nov 9, 2026
Merged

Brooooooklyn merged 2 commits into
oxc-project:mainfrom
darcyrush:fix/nodenext-commonjs-format

Conversation

@darcyrush

@darcyrush darcyrush commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

AI generated, but ran the fix against a dummy repo locally.

Fixes #907

Summary

Under module: node16, node18 and nodenext, tsc emits each .ts file in the format its
package.json "type" gives it, and a package without "type" is CommonJS. oxc-node's resolve hook
reported every .ts and .tsx file as an ES module under those settings instead. So TypeScript
written as CommonJS failed in "type": "commonjs" packages and in packages without a "type":

shape ("type": "commonjs", module: nodenext unless noted) before after
require / module.exports (also node16, node18) ESM: require is not defined in ES module scope CommonJS
import x = require() / export = TS(1202): Import assignment cannot be used when targeting ECMAScript modules CommonJS
CommonJS .ts file imported from an .mts file ESM: ReferenceError CommonJS
node:test file using import x = require(), run with --test TS(1202) passes
package without "type", require / module.exports ESM: ReferenceError CommonJS
module: node20 CommonJS unchanged
file with module syntax (import / export, import.meta, top-level await) ESM unchanged
module: es6, es2015 … esnext ESM unchanged

Fix

default_module_from_tsconfig no longer groups node16, node18 and nodenext with the ES module
settings. Only an ES module setting (es6, es2015, es2020, es2022, esnext) makes a .ts or
.tsx file an ES module. Under any other setting the package's "type" decides, as it already did
for 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 describe block in resolved-format.spec.ts (issue #907):

  • node16, node18, node20, nodenext: a .ts entry point, and a .tsx file imported from an
    .mts file, in a "type": "commonjs" package run as CommonJS.
  • nodenext: a .ts file without module syntax in a package without "type" runs as CommonJS.
  • nodenext: import x = require() plus export = in a "type": "commonjs" package runs as CommonJS.
  • Guards: a .ts file with export in a package without "type" still runs as an ES module;
    module: esnext still makes a .ts file an ES module.

With the src/lib.rs change reverted, five tests fail; node20 and the two guards pass either way.

Verification

  • Node.js 26.13: integration suite (600 passed, 7 skipped) and cargo test --all-features pass; cargo fmt, cargo clippy -D warnings,
    vp fmt --check and vp lint are clean.
  • Each shape above was run on tsc's output, on oxc-node from main, and on this branch. Every
    case that changed now matches tsc; no case moved away from it.

Not in scope

  • ES module syntax in a "type": "commonjs" package still runs as an ES module, where tsc would
    compile it to CommonJS (Clarify module resolution with .ts files using import and package.json type commonjs #905).
  • A CommonJS file that also has import type / export type / export interface still runs as an
    ES module, because type-only declarations count as module syntax.
  • With module: esnext, a file without module syntax still runs as an ES module, although tsc emits
    it as a script.
  • A .tsx file with no imports in a non-"type": "module" package now runs as CommonJS, like tsc,
    so a jsxImportSource that only resolves through tsconfig paths no longer resolves
    (CommonJS require does not use paths).

(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]>
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T03:50:58.753459Z e214f7f Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 8f3e89ab9a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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]>
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: e214f7f23c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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 Brooooooklyn left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! Verified against tsc emit and plain Node; all CI green.

@Brooooooklyn
Brooooooklyn enabled auto-merge (squash) November 9, 2026 04:16
@Brooooooklyn
Brooooooklyn disabled auto-merge November 9, 2026 08:30
@Brooooooklyn
Brooooooklyn merged commit 5a6aac8 into oxc-project:main Nov 9, 2026
67 checks passed
Brooooooklyn added a commit that referenced this pull request Nov 9, 2026
…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]>
Brooooooklyn added a commit that referenced this pull request Nov 11, 2026
… (#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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.ts files run as ES modules under tsconfig module: node16/node18/nodenext, ignoring package.json "type"

2 participants