Scripts y tareas
Automatizar flujos de trabajo
Scripts y tareas es una lección gratuita de Web3 & DApp Development Fundamentals en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Web3 & DApp Development Fundamentals, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Web3 & DApp Development Fundamentals incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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.jsAdd --network to target a specific network. Without it, the script runs against an ephemeral in-process network.
npx hardhat run scripts/deploy.js --network localhostThe 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 accountsIt also shows up under npx hardhat with its description, so teammates can discover it without reading the config.
npx hardhat accountsTask 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 vianpx hardhat runfor one-off jobs. - Tasks defined with
task()become first-class CLI commands. - The HRE exposes
ethers,network, andconfig. addParamadds CLI arguments;runSuperextends built-in tasks.- Subtasks compose internal steps callable with
hre.run.
Preguntas frecuentes
¿La lección «Scripts y tareas» es gratis?
Sí — el texto completo de «Scripts y tareas» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Web3 & DApp Development Fundamentals, actualiza a CoddyKit PRO. El curso de Web3 & DApp Development Fundamentals incluye 4 lecciones en total.
¿Qué aprenderé en «Scripts y tareas»?
Automatizar flujos de trabajo Practicas Web3 & DApp Development Fundamentals con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Web3 & DApp Development Fundamentals?
No se requiere experiencia previa. Web3 & DApp Development Fundamentals en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Scripts y tareas»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Web3 & DApp Development Fundamentals?
Sí. Cada lección de Web3 & DApp Development Fundamentals incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.