hardhat
hardhat copied to clipboard
HH5: HardhatContext is not created (possible cause & solution)
This isn't really a bug report, it just seemed the best place to put the info that might help someone.
I got this error when creating my typescript ESM deploy script. The cause is the specific order of imports.
In my scripts/deploy.ts file, I had the following includes:
import hre from 'hardhat';
import '@nomiclabs/hardhat-ethers';
import '@openzeppelin/hardhat-upgrades';
(psuedo) package.json:
"deploy": "yarn node ./scripts/deploy.ts"
This throws because the ethers & hardhat plugins are trying to access hre before it is created in the hardhat import.
Reversing the order of imports solves the problem.
NOTES (Why am I importing these packages in the script file?)
Normally, you don't need the hardhat-ethers and hardhat-upgrades imports in your script files, however with an ESM project there is a lot of fighting with module types. If we keep our hardhat.config.ts file with the project, hardhat cannot require it because the whole folder is an ESM module (renaming to .cts did not solve theproblem). To fix this, I moved the config file into my common contract-tools package that compiles as commonjs. However, then the trick of adding the config to tsconfig.json > files attribute seems not to work. Or at least, I couldn't seem to get it to play nice. TSC compiles & runs fine, it's just VS Code that reports (false) errors. To eliminate these annoying red squiggles, I added the imports here (node will ignore a re-import).
As hardhat doesn't support ESM modules (please support ESM!) this is more just a record in case anyone else stumbles down the same path.
This issue is also being tracked on Linear.
We use Linear to manage our development process, but we keep the conversations on Github.
LINEAR-ID: 60a44b94-21d5-4dc0-aded-5dc4f95b8c7f
Thanks for opening this issue! It sheds some light on why some users import the plugins like that.
Related to the discussion happening here: https://github.com/NomicFoundation/hardhat/issues/2945
Closing this in favor of https://github.com/NomicFoundation/hardhat/issues/3385