O I*_*uwa 3 javascript node.js solidity hardhat
所以我目前正在使用安全帽上的交易机器人进行练习。我的问题是,当我想运行我的脚本时,会出现此错误:
import './ABIConstants.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Run Code Online (Sandbox Code Playgroud)
有了这个建议:
(node:1284) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
Run Code Online (Sandbox Code Playgroud)
但是,当我按照它告诉我的那样设置“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).
Run Code Online (Sandbox Code Playgroud)
当我执行上述操作时,错误仍然存在......等等......
我该如何解决?
这是我用来运行脚本的命令(如果有帮助的话)
npx hardhat run scripts/ArbitrageBot.js
Run Code Online (Sandbox Code Playgroud)
Nodejs 中有两种模块 - 旧的 CommonJS 用于 require()加载其他 CommonJS 模块,而新的 ESM 用于import加载其他 ESM 模块?有几种方法可以混合和匹配模块类型,但这需要一些额外的知识,并且如果项目中的所有模块都属于同一类型,那么总是会更容易。因此,为了让我们为您的项目提供具体建议,我们需要了解您尝试在项目中使用的所有内容以及它们的模块类型。
您在问题中首先报告的具体错误是因为您试图import从 NodeJS 假设是 CommonJS 模块的文件中加载其他模块,而它不允许这样做。如果您正在编程的所有内容都是 CommonJS 模块,那么请切换到 userequire()来加载您的模块,而不是import. 但是,如果一切都不是 CommonJS 模块,那么它可能会更复杂一些。
文件扩展名(.mjs或.cjs)可以强制使用模块类型,或者"type": xxxpackage.json 中的 可以强制使用类型。默认情况下,如果没有这些,nodejs 会假设带有.js扩展名的顶级模块是 CommonJS 模块,您可以在其中require()加载其他 CommonJS 模块。
当您尝试强制顶级模块成为 ESM 模块时出现的第二个错误使得您尝试导入的模块听起来像是 CommonJS 模块。
因此,如果我不得不猜测,我会说您尝试导入的文件是 CommonJS 文件,因此,如果您将顶级文件设为 CommonJS,那么生活将变得最简单。为此,请"type": "module"从 package.json 中删除 并将其更改import someModule为require(someModule)。这将尝试让一切都是 CommonJS 模块。
| 归档时间: |
|
| 查看次数: |
5145 次 |
| 最近记录: |