Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS "Must use import to load ES Module"

I'm trying to import myArr from hello.js into index.js. However I get an error of

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module 

File hello.js

export let myArr = ['hello', 'hi', 'hey']; 

File index.js

import { myArr } from './hello.js'; console.log(myArr); 

Where am I going wrong?

like image 383
Elitezen Avatar asked May 08 '20 01:05

Elitezen


People also ask

How do I enable ES modules in node JS?

To be able to load an ES module, we need to set “type”: “module” in this file or, as an alternative, we can use the . mjs file extension as against the usual . js file extension. Also, from Node version 12.7.

How do I load ES module set type module in the package json?

// ⛔️ To load an ES module, set "type": "module" in // package. json import moment from 'moment'; moment(). format(); To be able to load ES modules, set the type property to module in your project's package.


2 Answers

Use version 2:

npm install node-fetch@2 

node-fetch from v3 is an ESM-only module - you are not able to import it with require().

If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.

like image 75
mal Avatar answered Sep 28 '22 22:09

mal


I ran your code without any problems. Check for two things:

  1. Node.js version >= 14. It only works with the latest version of Node.js.
  2. Make sure your package.json includes a line for "type": "module". Without this line, Node.js assumes you want to use CommonJS modules rather than ESM.
like image 44
G Clark Avatar answered Sep 28 '22 21:09

G Clark