Node: esm: provide more detailed error message when named import of cjs module

Created on 27 Aug 2020  路  5Comments  路  Source: nodejs/node

Is your feature request related to a problem? Please describe.
When I try to make named import for commonjs package, error throws:

The requested module 'redux' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.
For example:
import pkg from 'redux';
const { compose } = pkg;

In large project it can be hard to find in which file error is thrown

Describe the solution you'd like
It would be great append path to module, where

The requested from '/path/to/module.js' module 'redux' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.
For example:
import pkg from 'redux';
const { compose } = pkg;
ES Modules confirmed-bug

All 5 comments

Agreed, all ES module resolution errors are supposed to show the importer path, usually with "imported from X" at the end of the message. Adding that to this message would be worthwhile.

for message require is not defined too

We already indicate which position in which file is the problem at the first line of error. I don't think it's a good idea to just add the file path in the error message as well because it'll overlap the information.
If we'll suffix the message with import from X, we should remove the first line of the message I think.

$ cat test.mjs
import { createStore } from 'redux'

$ node -v
v14.8.0

$ node test.mjs
file:///Users/leko/ghq/github.com/Leko/node/tmp/test.mjs:1 <------------ HERE
import { createStore } from 'redux'
         ^^^^^^^^^^^
SyntaxError: The requested module 'redux' is expected to be of type CommonJS, which does not support named exports. CommonJS modules can be imported by importing the default export.
For example:
import pkg from 'redux';
const { createStore } = pkg;
    at ModuleJob._instantiate (internal/modules/esm/module_job.js:98:21)
    at async ModuleJob.run (internal/modules/esm/module_job.js:137:5)
    at async Loader.import (internal/modules/esm/loader.js:165:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5)

Ah, if the position is already available in the source location or stack trace then this is unnecessary yes. Closing, but let me know if I've missed anything too.

file:///Users/leko/ghq/github.com/Leko/node/tmp/test.mjs:1 <------------ HERE

will it be ported to 12.x ?

upd:
hmmm, somehow it now works for me on 12.x. maybe lerna hided some messages. Sorry

Was this page helpful?
0 / 5 - 0 ratings