0Pricing
Web3 & DApp Development Fundamentals · 课时

脚本与任务

自动化工作流

脚本与任务 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web3 & DApp Development Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Scripts vs Tasks

Hardhat offers two ways to automate work:

  • Scripts — plain Node.js files you run for one-off jobs like deployment.
  • Tasks — reusable commands integrated into the Hardhat CLI with arguments and help text.

Use scripts for ad-hoc automation, tasks for repeatable commands your team reuses.

A Deployment Script

Scripts live in scripts/. A deploy script uses ethers from the Hardhat Runtime Environment:

const hre = require("hardhat"); async function main() { const Greeter = await hre.ethers.getContractFactory("Greeter"); const greeter = await Greeter.deploy(); await greeter.waitForDeployment(); console.log("Deployed to:", await greeter.getAddress()); } main();
const hre = require("hardhat");

async function main() {
  const Greeter = await hre.ethers.getContractFactory("Greeter");
  const greeter = await Greeter.deploy();
  await greeter.waitForDeployment();
  console.log("Deployed to:", await greeter.getAddress());
}

main();

Running a Script

Run a script through Hardhat so it injects the runtime environment and network:

npx hardhat run scripts/deploy.js

Add --network to target a specific network. Without it, the script runs against an ephemeral in-process network.

npx hardhat run scripts/deploy.js --network localhost

The Runtime Environment

The Hardhat Runtime Environment (HRE) is injected automatically and gives you:

  • hre.ethers — the ethers.js helpers.
  • hre.network — info about the active network.
  • hre.config — the resolved configuration.

Inside tasks the HRE is the second argument; in scripts it is the hardhat module.

Defining a Custom Task

Define tasks in hardhat.config.js using the task helper:

const { task } = require("hardhat/config"); task("accounts", "Prints the list of accounts", async (taskArgs, hre) => { const accounts = await hre.ethers.getSigners(); for (const account of accounts) { console.log(account.address); } });
const { task } = require("hardhat/config");

task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
  const accounts = await hre.ethers.getSigners();
  for (const account of accounts) {
    console.log(account.address);
  }
});

Running a Custom Task

Once defined, your task appears in the CLI like any built-in command:

npx hardhat accounts

It also shows up under npx hardhat with its description, so teammates can discover it without reading the config.

npx hardhat accounts

Task Parameters

Tasks accept named parameters with addParam:

task("balance", "Prints an account balance") .addParam("account", "The address") .setAction(async (taskArgs, hre) => { const bal = await hre.ethers.provider.getBalance(taskArgs.account); console.log(hre.ethers.formatEther(bal), "ETH"); });

Run it with npx hardhat balance --account 0x....

task("balance", "Prints an account balance")
  .addParam("account", "The address")
  .setAction(async (taskArgs, hre) => {
    const bal = await hre.ethers.provider.getBalance(taskArgs.account);
    console.log(hre.ethers.formatEther(bal), "ETH");
  });

Overriding Built-in Tasks

You can extend existing tasks like compile using the same name. Use runSuper to call the original behavior:

task("compile", async (args, hre, runSuper) => { console.log("Before compiling..."); await runSuper(args); console.log("Done compiling!"); });

This is handy for adding logging or post-processing steps.

task("compile", async (args, hre, runSuper) => {
  console.log("Before compiling...");
  await runSuper(args);
  console.log("Done compiling!");
});

Subtasks

Subtasks are internal tasks not shown in the main help list. They let you break complex tasks into reusable pieces:

const { subtask } = require("hardhat/config"); subtask("print-network", async (args, hre) => { console.log("Network:", hre.network.name); });

Call subtasks from other tasks with hre.run("print-network").

const { subtask } = require("hardhat/config");

subtask("print-network", async (args, hre) => {
  console.log("Network:", hre.network.name);
});

When to Use Each

Rules of thumb:

  • Need a quick deploy or migration? Write a script.
  • Need a reusable command with parameters and help text? Write a task.
  • Need to compose internal steps? Use subtasks.

Both scripts and tasks have full access to the HRE.

Scripts in package.json

For convenience, wrap common commands as npm scripts:

{ "scripts": { "deploy": "hardhat run scripts/deploy.js --network localhost", "test": "hardhat test" } }

Then teammates run npm run deploy without memorizing flags.

{
  "scripts": {
    "deploy": "hardhat run scripts/deploy.js --network localhost",
    "test": "hardhat test"
  }
}

Quick Check

Test your understanding of scripts and tasks.

Recap

You learned how to automate Hardhat workflows.

  • Scripts in scripts/ run via npx hardhat run for one-off jobs.
  • Tasks defined with task() become first-class CLI commands.
  • The HRE exposes ethers, network, and config.
  • addParam adds CLI arguments; runSuper extends built-in tasks.
  • Subtasks compose internal steps callable with hre.run.

常见问题解答

「脚本与任务」课时是免费的吗?

是的 — 「脚本与任务」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

「脚本与任务」这节课中我会学到什么?

自动化工作流 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web3 & DApp Development Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「脚本与任务」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?

能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 设置 Hardhat
  2. 编译合约
  3. 脚本与任务
  4. 本地网络与分叉
← 返回 Web3 & DApp Development Fundamentals