NodeJS 而是改变索引的要求,js,到一个动态import(),它在所有CommonJS模块中都可用

xytpbqjk  于 2023-04-29  发布在  Node.js
关注(0)|答案(7)|浏览(245)

尝试使用node/javascript/nfts,我是一个新手,并沿着了教程,但我得到了这个错误:

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

我的理解是,他们已经更新了节点文件,所以我需要一个不同的代码比在教程中,但我不知道哪一个我应该改变,在哪里和什么。请尽可能具体地说

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));
})
sg24os4d

sg24os4d1#

这是因为node-fetch封装。由于此软件包的最新版本仅支持ESM,因此您必须将其降级到旧版本node-fetch@2.6.1或更低版本。
npm i node-fetch@2.6.1
这应该可以解决问题。

ijnw1ujt

ijnw1ujt2#

不需要使用旧版本。你可以用这一行代替“require”

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

ohtdti5x3#

当您安装的软件包的最新版本在模块导入方面存在问题时,可能会发生这种情况。
在我的情况下,我是在安装最新版本的crypto-random-string包后得到错误的。要知道是哪个软件包导致此错误,请检查报告的上述错误之前的消息。在我的例子中,它是这样读的:error: uncaughtException: require() of ES Module /Users/myname/Documents/mydir/anotherdir/my-project/node_modules/crypto-random-string/index.js
为了解决这个问题,我只能通过执行以下操作降级到早期版本:

  1. yarn remove crypto-random-string
  2. yarn add crypto-random-string@3.3.1
rm5edbpk

rm5edbpk4#

去你的包裹。json文件并写入:

"type": "module",

上面的debug。
而不是在中写入require('chalk')。js文件,更改为import chalk from 'chalk'

6mzjoqzu

6mzjoqzu5#

我在共同的时候犯了这个错误。js在angular-devkit升级到angular 13后。我发现在升级过程中遗漏了这一点:
ng update does not check or update @angular-devkit packages
我摆脱了它使用:

ng update @angular-devkit/build-angular
xu3bshqb

xu3bshqb6#

另一个对我有用的选择是使用包node-fetch-native,它用一些polyfill重新分发node-fetch

hrysbysz

hrysbysz7#

我额外添加了一个语句,您可以看到这个"type": "module",语句,写在license之后。

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

相关问题