esm import throws error in node
detj opened this issue · 4 comments
Problem
On trying to esm import in node 14.16.0, getting the following error.
import { Env } from "@humanwhocodes/env";
^^^
SyntaxError: Named export 'Env' not found. The requested module '@humanwhocodes/env' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from '@humanwhocodes/env';
const { Env } = pkg;
at ModuleJob._instantiate (internal/modules/esm/module_job.js:104:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:149:5)
at async Loader.import (internal/modules/esm/loader.js:166:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
Steps to reproduce
- create an empty directory & cd into it -
mkdir env-try && cd env-try
- create a fresh package.json -
npm init --yes
- edit root package.json to add
"type": "module"
- install pkg -
npm install @humanwhocodes/env
- create new file with following contents -
touch index.js
import { Env } from "@humanwhocodes/env";
const env = new Env();
console.log(env);
- On running using
node index
throws the above error.
Notes
The package's package.json file correctly specifies "export" field as per node's conditional exports, but I'm not sure why this error gets thrown. Not sure if this issue is related to node's esm import support.
Although, adding "type": "module"
in env's package.json solves this issue & the exported member is imported.
Am I missing something here, any idea?
node -v
v14.16.0
npm -v
7.6.0
I ran into this too. I believe this is because Node will treat any imported JavaScript file as CommonJS unless:
- the
package.json
for the imported module hastype: module
, or - the imported file extension is
.mjs
Here's where I worked through it: https://github.com/m-allanson/node-esm-resolution.
I think adding type: module
would break the CommonJS imports? But changing the ESM file extension to .mjs
should work (which is option 1 in this article).
Thanks for the report. I'm not sure how I missed it, but I'll dig in and see if I can set up some automation to make sure this is caught with CI from now.
This should be fixed in v2.1.3. Let me know if it's still not working.
tested. works flawlessly.