DB *_*ire 11 javascript parameters command-line hardhat
我需要从命令行使用 Hardhat 运行特定的 ts 脚本,但我需要指定参数...与此类似:
npx hardhat run --network rinkeby scripts/task-executor.ts param1 param2
Run Code Online (Sandbox Code Playgroud)
其中是hardhat 运行--network rinkeby的参数
, 和是task-executor.ts脚本的参数。
我找不到任何有关此问题的帖子,也无法使其工作。param1param2
我还尝试定义一个安全帽任务并添加这些参数,但如果我尝试执行它,我会得到:
Error HH9: Error while loading Hardhat's configuration.
You probably tried to import the "hardhat" module from your config or a file imported from it.
This is not possible, as Hardhat can't be initialized while its config is being defined.
Run Code Online (Sandbox Code Playgroud)
因为我需要在该特定任务中导入hre或ethers导出。hardhat
如何完成我所需要的?
jpo*_*zzi 13
根据安全帽:
Hardhat 脚本对于不接受用户参数的简单操作以及与不太适合 Hardhat CLI 的外部工具(例如 Node.js 调试器)集成非常有用。
对于需要参数的脚本,您应该使用Hardhat Tasks。
您可以在与Hardhat.config.ts不同的文件中编写该任务。以下是使用文件SampleTask.ts中的位置参数的示例任务:
import { task } from "hardhat/config";
task("sampleTask", "A sample task with params")
.addPositionalParam("param1")
.addPositionalParam("param2")
.setAction(async (taskArgs) => {
console.log(taskArgs);
});
Run Code Online (Sandbox Code Playgroud)
请记住将其导入到hardhat.config.ts中:
import "./tasks/sampleTask";
Run Code Online (Sandbox Code Playgroud)
然后运行它:
npx hardhat sampleTask hello world
Run Code Online (Sandbox Code Playgroud)
它应该打印:
{ param1: 'hello', param2: 'world' }
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关任务的命名参数、位置参数和可选参数的更多信息。
如果需要使用hreor ethers,可以hre从函数的第二个参数中获取setAction:
task("sampleTask", "A sample task with params")
.addPositionalParam("param1")
.addPositionalParam("param2")
.setAction(async (taskArgs, hre) => {
const ethers = hre.ethers;
});
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用环境并通过 process.env 访问
在 Linux 上:
param1=some param2=thing npx hardhat run scripts/task-executor.ts
Run Code Online (Sandbox Code Playgroud)
并打印:
console.log(process.env.param1);
Run Code Online (Sandbox Code Playgroud)