Basse Nord
Basse Nord

Reputation: 2123

Instead change the require of index.js, to a dynamic import() which is available in all CommonJS modules

Trying to work with node/javascript/nfts, I am a noob and followed along a tutorial, but I get this error:

error [ERR_REQUIRE_ESM]: require() of ES Module [...] is not supported. Instead change the require of index.js [ in my file...]  to a dynamic import() which is available in all CommonJS modules

My understanding is that they've updated the node file, so i need a different code than that in the tutorial, but i don't know which one I'm supposed to change, where and to what. Please be as specific as you can

const FormData = require('form-data');
const fetch = require('node-fetch');
const path = require("path")
const basePath = process.cwd();
const fs = require("fs");

fs.readdirSync(`${basePath}/build/images`).foreach(file).forEach(file => {
    const formData = new FormData();
    const fileStream = fs.createReadStream(`${basePath}/build/images/${file}`);
    formData.append('file',fileStream);

    let url = 'https://api.nftport.xyz/v0/files';

    let options = {
      method: 'POST',
      headers: {
        Authorization: '[...]',
      },
      body: formData
    };
    
    fetch(url, options)
      .then(res => res.json())
      .then(json => {
       const fileName = path.parse(json.file_name).name;
       let rawdata = fs.readFileSync(`${basePath}/build/json/${fileName}.json`);
       let metaData = JSON.parse(rawdata);

       metaData.file_url = json.ipfs_url;

       fs.writeFileSync(`${basePath}/build/json${fileName}.json`, JSON.stringify(metaData, null, 2));

       console.log(`${json.file_name} uploaded & ${fileName}.json updated!`);
      })
      .catch(err => console.error('error:' + err));
})

Upvotes: 208

Views: 313165

Answers (12)

Mayank Kumar Chaudhari
Mayank Kumar Chaudhari

Reputation: 18538

There are multiple ways to solve this problem.

  1. downgrade package -- not recommended, you are missing on new features and security fixes.

  2. Use dynamic import, which is supported in common JS. import('your-package').then(...)

  3. Use .mjs extension for your file and use import instead of require. By default, this will be treated as an ESM file.

  4. Add "type": "module" in your package.json

Upvotes: 1

ABDULLOKH MUKHAMMADJONOV
ABDULLOKH MUKHAMMADJONOV

Reputation: 5234

It is because of the node-fetch package. As recent versions of this package only supports ESM; you have to downgrade it to an older version [email protected] or lower.

npm i [email protected]

This should solve the issue.

Upvotes: 178

massika
massika

Reputation: 1

If you are running Ubuntu, then remove npm from: /usr/local/lib/node_modules/npm & /usr/local/bin/npm

Check node Version: node -v

Clear Cache: rm -rf ~/.npm

Finally, reinstall npm@latest version:

curl -qL https://www.npmjs.com/install.sh | sh

Upvotes: 0

Chinenye anazo
Chinenye anazo

Reputation: 1

For me what worked was using node version 20.1.0 as i had nvm as my package manager. if you use nvm you can do so by using nvm use 20.1.0 if you have the version or nvm install 20.1.0 if you do not have 20.1.0

Upvotes: 0

danday74
danday74

Reputation: 56936

ps-list is an example package with this issue. This works:

(async () => {
  const psList = await import('ps-list').then(psl => psl.default)
  // YOUR CODE HERE
})().catch(console.error)

This also logs on error instead of remaining silent!

This answer is essentially the same but I found it somewhat confusing and it doesn't handle errors! https://stackoverflow.com/a/75281896/1205871

Upvotes: 6

Boern
Boern

Reputation: 7752

In your .tsconfig:

change "module": "nodenext", to "module": "commonjs", if your projects allows.

Upvotes: 1

David Dal Busco
David Dal Busco

Reputation: 8642

Another option that worked for me is using the package node-fetch-native that redistributes node-fetch with some polyfill.

Upvotes: 1

Itzik
Itzik

Reputation: 565

No need to use the old version. You can use this line instead of "require"

const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

Upvotes: 57

Mona Thahmeen
Mona Thahmeen

Reputation: 237

Go to your package.json file and write:

"type": "module",

above debug.

and instead of writing require('chalk') in the .js file, change it to import chalk from 'chalk'

Upvotes: 12

Majid Ali
Majid Ali

Reputation: 13

I added the one statement extra you can see this "type": "module", statement, written down after license.

"author": "",
  "license": "ISC",
  "type": "module",
  "dependencies": {
    "chalk": "^5.0.1"
    
  }
}

Upvotes: -5

Hameed Damee
Hameed Damee

Reputation: 321

This can occur when you install the latest version of a package that has an issue with modules import.

In my case, I was getting the error after installing the latest version of crypto-random-string package. To know which package is causing this error, check the message preceding the above error reported. In my case, it read like so: error: uncaughtException: require() of ES Module /Users/myname/Documents/mydir/anotherdir/my-project/node_modules/crypto-random-string/index.js

To fix it, I only downgraded to an earlier version by doing the following:

  1. yarn remove crypto-random-string
  2. yarn add [email protected]

Upvotes: 14

Ger
Ger

Reputation: 191

I had this error on common.js in angular-devkit after upgrading to angular 13. I found that this is missed during the upgrade:

ng update does not check or update @angular-devkit packages

I got rid of it using:

ng update @angular-devkit/build-angular 

Upvotes: 4

Related Questions