Skip to content
This repository was archived by the owner on Sep 2, 2023. It is now read-only.
This repository was archived by the owner on Sep 2, 2023. It is now read-only.

Improve error message when attempting to require(esm) #523

@dfabulich

Description

@dfabulich
// foo.mjs
export const foo = 'bar';

// index.js
require('./foo.mjs');
$ node index.js
internal/modules/cjs/loader.js:1047
    throw new ERR_REQUIRE_ESM(filename);
    ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /tmp/foo.mjs
    at Module.load (internal/modules/cjs/loader.js:1047:11)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Module.require (internal/modules/cjs/loader.js:1089:19)
    at require (internal/modules/cjs/helpers.js:73:18)
    at Object.<anonymous> (/tmp/1/index.js:1:1)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) {
  code: 'ERR_REQUIRE_ESM'
}
  1. The message "Must use import to load ES Module" won't mean anything to users who don't understand the difference between CJS and ESM. If anything, I think it would encourage them to try import './foo.mjs' which is not going to work in a CJS script.

    I suggest something like:

    Error [ERR_REQUIRE_ESM]: This is an ES Module; it can't be loaded with require: /tmp/foo.mjs
    You can import it asynchronously with import(), or you can import it from an ES Module. See [link]

  2. The top part of this stack points to internal/modules/cjs/loader.js; it should point to index.js

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions