Skip to content

detect-module: confusing error when parsing a CommonJS module with top-level await #55776

Open
@GeoffreyBooth

Description

@GeoffreyBooth

Porting from nodejs/TSC#1445 (comment):

index.js:

const {
    getPort,
    checkPort,
    getRandomPort,
    waitForPort,
} = require("get-port-please")

const port = await getPort()

Getting this:

Restarting 'index.js'
(node:15356) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///C:/Users/Babak/Documents/Code/c12/index.js is not specified and it doesn't parse as CommonJS.
Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
To eliminate this warning, add "type": "module" to C:\Users\Babak\Documents\Code\c12\package.json.
(Use `node --trace-warnings ...` to show where the warning was created)
file:///C:/Users/Babak/Documents/Code/c12/index.js:7
} = require("get-port-please")
    ^

ReferenceError: require is not defined in ES module scope, you can use import instead
    at file:///C:/Users/Babak/Documents/Code/c12/index.js:7:5
    at ModuleJob.run (node:internal/modules/esm/module_job:262:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:483:26)

Node.js v22.9.0
Failed running 'index.js'

With this package.json:

{
    "dependencies": {
        "express": "4.21.0",
        "get-port-please": "3.1.2"
    },
    "devDependencies": {
        "@types/express": "5.0.0"
    }
}

LOL. (await 😈).

Originally posted by @babakfp in nodejs/TSC#1445 (comment)


So basically, this module fails to parse as either CommonJS or as ESM, and we show the ESM parsing error message. Perhaps we should show both, or show a special message for the common use case of using top-level await in a CommonJS module.

Metadata

Metadata

Assignees

No one assigned

    Labels

    esmIssues and PRs related to the ECMAScript Modules implementation.moduleIssues and PRs related to the module subsystem.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions