相反,将 index.js 的要求更改为动态 import() ,该 import()在所有 CommonJS 模块中都可用

在尝试使用 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));
})


79939 次浏览

这是因为 node-fetch包。由于该软件包的最新版本只支持 ESM,因此必须将其降级到较旧版本的 node-fetch@2.6.1或更低版本。

npm i node-fetch@2.6.1

这应该能解决问题。

转到 package.json 文件并编写

"type": "module",

在调试之上。

并将其改为 import chalk from 'chalk',而不是将 require('chalk')写入 js 文件

升级到 angle 13之后,我在 angle-devkit 中的 common.js 上出现了这个错误。我发现在升级过程中遗漏了这一点:

Ng update 不检查或更新@angle-devkit 包

我用以下方法摆脱了它:

ng update @angular-devkit/build-angular

在安装存在模块导入问题的包的最新版本时,可能会发生这种情况。

在我的例子中,我是在安装了最新版本的 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

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

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

}
}