2

The hardhat testing tutorial uses require for imports, and not import.

This site describes CommonJS using require and ESModule as using import.

I have some code that uses ESModule style (exports and imports), and I can't easily use it in Hardhat code.

How do I use the ESModule-style code in hardhat?

When running npx hardhat test

  • If I use ESModule style import in the hardhat code, I get the error you would expect:
An unexpected error occurred:

.../solidity/test/some_code.js:6
import { aSymbol } from "../blah/src/utils/helpers"
^^^^^^
  • If I use require in the hardhat code, I get complaints you'd expect about the ESModule style export:
.../blah/src/utils/helpers.js:35
export async function aSymbol() {
^^^^^^

SyntaxError: Unexpected token 'export'
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (.../solidity/test/some_code.js:5:6)

EDIT: This may be related, still reading.

dfrankow
  • 20,191
  • 41
  • 152
  • 214
  • Oh, maybe I can use this awful-looking "Universal Module Definition": https://riptutorial.com/javascript/example/16339/universal-module-definition--umd- – dfrankow Dec 14 '21 at 00:11
  • UMD is old technology that was meant to support Node/CommonJS modules in browsers (think webpack/browserify). It does not support ESM imports (at least not if you're writing it yourself). You can of course use something like webpack to "compile" your ESM files into UMD (webpack) modules which you can then require. – slebetman Dec 14 '21 at 02:05
  • How do I do this exactly? It appears involved, and I don't see examples out there. – dfrankow Dec 14 '21 at 15:19

1 Answers1

-1

You can use the esm module. First install it running npm i --save-dev esm. Then add a hardhat script in your package.json file as follows:

"scripts": {
    "hardhat": "node --require esm node_modules/.bin/hardhat",

then use hardhat through npm run hardhat instead of hardhat command.