提问者:小点点

在node js中导入时加载“ES模块”的问题[重复]


所以我目前正在使用hardhat上的交易机器人进行练习。我的问题是,当我想运行我的脚本时,会出现这个错误:

    import './ABIConstants.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module

有了这个建议:

(node:1284) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

然而,当我按照告诉的那样做并设置“type”:“module”时,我会得到以下错误:

hardhat.config.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead rename hardhat.config.js to end in .cjs, change the requiring code to use dynamic import() which is avakage.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

当我做上述操作时,错误仍然存在....等等....

我该如何解决这个问题?

如果有帮助的话,下面是我用来运行脚本的命令

npx hardhat run scripts/ArbitrageBot.js

共1个答案

匿名用户

nodejs中有两种模块-旧的CommonJS使用require()来加载其他CommonJS模块,而新的ESM使用import加载其他ESM模块?有几种方法可以混合和匹配模块类型,但这需要一些额外的知识,而且如果项目中的所有模块都是同一类型,那么这总是更容易的。因此,为了让我们为您的项目提供具体建议,我们需要了解您试图在项目中使用的所有内容,以及它们都是什么模块类型。

您在问题中第一次报告的具体错误是,您正试图使用<code>import</code>从nodejs认为是CommonJS模块的文件中加载其他模块,但它不允许这样做。如果您正在使用的所有编程都是CommonJS模块,那么切换到使用require()来加载您的模块,而不是import。但是,如果一切都不是CommonJS模块,那么它可能会更加复杂。

文件扩展名(<code>.mjs</code>或<code>.cjs<-code>)可以强制模块类型,或者package.json中的<code>“type”:xxx</code>可以强制类型。默认情况下,在这两个模块都不存在的情况下,nodejs假设具有<code>.js</code>扩展的顶级模块是CommonJS模块,您将使用<code>require()</code>加载其他CommonJS模块。

当您尝试强制顶级模块成为ESM模块时,您遇到的第二个错误听起来像您尝试导入的模块是CommonJS模块。

所以,如果非要我猜测的话,我会说你试图导入的文件是一个CommonJS文件,因此,如果你制作了顶级文件CommonJS,生活会最轻松。要做到这一点,请从package.json中删除“type”:“module”,并将导入someModule更改为需要(someModule)。这将试图让一切都成为CommonJS模块。