Closed kanej closed 3 weeks ago
Hardhat can also be used from plain node scripts, passing a config programmatically or relying on implicit file loading.
A small clarification. This can also be done with any script. These other lower-level apis are just for advanced/non-standard things.
readHardhatConfig
I think exporting a function that finds the config file is also helpful, and may even be a better alternative to readHardhatConfig
.
Hardhat can also be used from plain node scripts, passing a config programmatically or relying on implicit file loading.
A small clarification. This can also be done with any script. These other lower-level apis are just for advanced/non-standard things.
readHardhatConfig
I think exporting a function that finds the config file is also helpful, and may even be a better alternative to
readHardhatConfig
.
Can you provide example code, I am not sure I have followed what your preference is here?
Sure.
You can run a hardhat script with node script.js
. As in v3 you have to import hardhat, that import will initialize the HRE.
/// script.js
import {config} from "hardhat";
console.log(config);
Or, if it was about the second part:
import { createHardhatRuntimeEnvironment, findHardhatConfigFile } from "hardhat/hre"
const configPath = await findHardhatConfigFile()
const {default: config} = await import(configPath);
const hre = await createHardhatRuntimeEnvironment(config, configPath) // Note the configPath, to be used to determine the project root.
console.log(hre.config.solidity)
The Hardhat run task enables js/ts scripts to be run in a node environment and leverage a HardhatRuntimeEnvironment generated based on the given hardhat.config.{js,ts}:
In both JavaScript and Typescript the HardhatRuntimeEnvironment needs to be imported:
JavaScript:
Typescript:
The
HardhatRuntimeEnvironment
that is initialized will by default be based on the closesthardhat.config.{js,ts}
, where closest mean looking in the current working directory, then moving to the parent directory recursively.The
hardhat.config.{js,ts}
that is used can be overridden on the command line with the--config
flag.A Typescript script will be executed with
tsx
.Running with bare node
Hardhat can also be used from plain node scripts, passing a config programmatically or relying on implicit file loading.
Passing the config programmatically:
Reading the config from the local
hardhat.config.{js,ts}
: