3

So I am currently practicing with a trading bot on hardhat. My problem is, when I want to run my script this error shows up:

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

SyntaxError: Cannot use import statement outside a module

with this suggestion:

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

However, when I do as it tells me and set "type":"module" I get this error:

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).

And the errors continue as I do the above....etc....

How do I fix this?

Heres the command I am using to run the script if it helps

npx hardhat run scripts/ArbitrageBot.js
O Inuwa
  • 91
  • 1
  • 5

1 Answers1

6

There are two kinds of modules in nodejs - the older CommonJS which uses require() to load other CommonJS modules and the newer ESM which uses import to load other ESM modules? There are a few ways to mix and match module types, but that requires some additional knowledge and it is always easier if all the modules in your project are of the same type. So, for us to offer specific advice on your project, we need to know everything that you're trying to use in your project and what module type they all are.

The specific error you first report in your question is because you are trying to use import to load other modules from a file that nodejs is assuming is a CommonJS module and it will not allow that. If everything you are programming with is CommonJS modules, then switch to use require() to load your module instead of import. But, if everything isn't CommonJS modules, then it may be a bit more complicated.

The file extension (.mjs or .cjs) can force a module type or the "type": xxx in package.json can force a type. By default, with neither of those in place nodejs assumes your top level module with a .js extension is a CommonJS module where you would use require() to load other CommonJS modules.

The second error you get when you tried to force your top level module to be an ESM module makes it sounds like the module you are trying to import is a CommonJS module.

So, if I had to guess, I'd say the file you are trying to import is a CommonJS file and therefore, life would be easiest if you made your top level file CommonJS. To do that, remove the "type": "module" from package.json and change your import someModule to require(someModule) instead. This will attempt to just let everything be CommonJS modules.

jfriend00
  • 683,504
  • 96
  • 985
  • 979