Skip to content

Clarify module resolution with .ts files using import and package.json type commonjs #905

Closed

Description

@darcyrush

It seems that oxc-node prioritizes the import notation of TypeScript within a file over the projects package.json type entry.

// package.json
{
  "type": "commonjs",   // CJS
  "scripts": {
    "test": "oxnode --test 'tests/test.ts'"
  },
  "devDependencies": {
    "@oxc-node/cli": "1.0.1",
    "typescript": "7.0.2"
  }
}
// test.ts

import { test } from "node:test";
import { equal } from "node:assert/strict";
import * as Example from "../src/lib";
import { execute } from "../src/app";

test("example", async ({ mock }) => {
  mock.method(Example, "func", () => "mocked");
  equal(execute(), "mocked");
});
$ oxnode --test 'test.ts'

test at test.ts:7:1
✖ example (0.672184ms)
  TypeError [Error]: Cannot redefine property: func

I found this a bit surprising, but the LLMs say this aligns with Node's type stripping rather than tsc.

If this is the case, perhaps the README and documentation can be clarified?

A file is an ES module when its extension or package.json says so, or when it uses import, export, import.meta or top-level await. Other files run as CommonJS, even when tsconfig.json sets an ES module.

To me, this reads like the priority is;

extension -> package.json -> import

If the extension is .ts (ambiguous), I would assume the next priority would be to read the package.json type property which in this case is commonjs.

However, this doesn't seem to be the case - my .ts files using import notation are treated as ESM rather than CJS as defined in package.json.


Still, if this is by design; is there an escape hatch I can use with oxc-node? Like a command line flag or ENV variable to force a particular module resolution?

I would rather not rewrite the entire codebase using require instead of import - the idea is that when Node stabilizes ESM mocking, the tests are migrated from mock.method to mock.module and the package.json type is flipped from commonjs to module.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions