Skip to content

fix(core): run files whose only imports and exports are type-only as CommonJS - #910

Merged
Brooooooklyn merged 6 commits into
oxc-project:mainfrom
darcyrush:fix/type-only-commonjs
Nov 9, 2026
Merged

Brooooooklyn merged 6 commits into
oxc-project:mainfrom
darcyrush:fix/type-only-commonjs

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 #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.

@darcyrush
darcyrush force-pushed the fix/type-only-commonjs branch from 9e55fb1 to bda8cec Compare November 6, 2026 16:28
@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-09T09:55:05.050758Z e093b02 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bda8ceca66

ℹ️ 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".

Comment thread src/lib.rs Resolved
Comment thread src/lib.rs Resolved
Brooooooklyn and others added 2 commits November 9, 2026 16:48
- Don't compile a file whose only imports and exports are type-only as
  CommonJS when Node.js runs it as an ES module whatever its syntax: a
  `.mts` file, or a `.ts` file in a "type": "module" package. The
  `pirates` hook and `transform()` pass `is_es_module: false` for every
  file, so a `require()`d one ran as CommonJS, and ran a second time
  when it was also imported.
- Keep such a file an ES module when it binds `require`, `module`,
  `exports`, `__filename` or `__dirname` with `let`, `const`, `using` or
  `class`, as Node.js' syntax detection does. It crashed with
  ERR_REQUIRE_CYCLE_MODULE.
- Skip the second `parsed_as_esm` call on the load-hook path.
- Test both cases and the `transform()` output; README: type-only
  imports and exports don't make an importer file an ES module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 381db7196c

ℹ️ 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".

Comment thread src/lib.rs Resolved
Comment thread src/lib.rs Resolved
… CommonJS

- Don't compile a type-only file as CommonJS for `require()` when its
  tsconfig sets an ES `module`: the resolve hook reports it as an ES
  module for `import`, so `require()` and `import()` of the same file
  ran it twice. The check shares `is_es_module_setting` with
  `default_module_from_tsconfig`.
- Treat `import type X = require()` as erased: it no longer vetoes ES
  module detection, so a file that also has top-level await runs as an
  ES module again instead of failing the CommonJS transform, and it
  counts as a type-only declaration, so alone it stays CommonJS.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c72d3e1fdf

ℹ️ 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".

Comment thread src/lib.rs Resolved
…ommonJS

The importer decides a file's format from its syntax and package.json
alone, whatever the tsconfig says. Under an ES tsconfig `module`, the
previous commit kept a type-only file's source type a module on that
path too, so a helper it needed (a legacy decorator's, for one) was
emitted as an import, which the importer's CommonJS wrapper cannot run.
Apply the tsconfig check only outside the importer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 775c46a854

ℹ️ 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".

Comment thread src/lib.rs Resolved
An alias such as `import C = N.C` compiles to a plain binding, not to
`require()`, but it vetoed ES module detection like `import x =
require()`. With a type-only import no longer counting as module
syntax, a file with such an alias and top-level await went to the
CommonJS transform, which rejects the await. Only an external module
reference now vetoes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e093b02ad4

ℹ️ 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".

Comment thread src/lib.rs Resolved
@Brooooooklyn
Brooooooklyn merged commit 75617f0 into oxc-project:main Nov 9, 2026
131 of 132 checks passed
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 whose only imports and exports are type-only run as ES modules, without require or module

2 participants