0Pricing
Web3 & DApp Development Fundamentals · Leçon

Scripts et tâches

Automatiser les flux de travail

Scripts et tâches est une leçon Web3 & DApp Development Fundamentals gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Web3 & DApp Development Fundamentals, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Web3 & DApp Development Fundamentals comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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.

Questions Fréquemment Posées

La leçon « Scripts et tâches » est-elle gratuite ?

Oui — le texte complet de « Scripts et tâches » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Web3 & DApp Development Fundamentals, passe à CoddyKit PRO. Le cours Web3 & DApp Development Fundamentals comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Scripts et tâches » ?

Automatiser les flux de travail Tu pratiques Web3 & DApp Development Fundamentals avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Web3 & DApp Development Fundamentals ?

Aucune expérience préalable n'est requise. Web3 & DApp Development Fundamentals sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.

Combien de temps prend la leçon « Scripts et tâches » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Web3 & DApp Development Fundamentals ?

Oui. Chaque leçon Web3 & DApp Development Fundamentals inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Configuration de Hardhat
  2. Compiler des contrats
  3. Scripts et tâches
  4. Réseau local et fork
← Retour à Web3 & DApp Development Fundamentals