【问题标题】:Problem with loading "ES module" when importing in node js [duplicate]在节点js中导入时加载“ES模块”的问题[重复]
【发布时间】:2022-01-24 09:03:46
【问题描述】:

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

    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

【问题讨论】:

标签: javascript node.js solidity hardhat


【解决方案1】:

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

您在问题中首先报告的具体错误是因为您试图使用 import 从 nodejs 假设为 CommonJS 模块的文件中加载其他模块,并且它不允许这样做。如果您正在编程的所有内容都是 CommonJS 模块,那么请切换到使用 require() 而不是 import 来加载您的模块。但是,如果一切都不是 CommonJS 模块,那么它可能会更复杂一些。

文件扩展名(.mjs 或 .cjs)可以强制一个模块类型,或者 package.json 中的 "type": xxx 可以强制一个类型。默认情况下,这些都没有,nodejs 假定您的顶级模块具有 .js 扩展名是 CommonJS 模块,您可以使用 require() 加载其他 CommonJS 模块。

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

所以,如果我不得不猜测,我会说您尝试导入的文件是 CommonJS 文件,因此,如果您制作顶级文件 CommonJS.为此,请从 package.json 中删除 "type": "module" 并将您的 import someModule 更改为 require(someModule)。这将试图让一切都是 CommonJS 模块。

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 2021-12-02
    • 2020-08-23
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2018-07-02
    • 1970-01-01
    相关资源
    最近更新 更多