0
0
DenoHow-ToBeginner ยท 3 min read

How to Define Tasks in deno.json for Deno CLI

In deno.json, define tasks inside the tasks object as key-value pairs where keys are task names and values are command strings or arrays. You can then run these tasks with deno task <task-name> to automate common commands.
๐Ÿ“

Syntax

The tasks field in deno.json is an object where each key is a task name and the value is either a string command or an array of strings representing the command and its arguments.

  • Task name: The key used to run the task.
  • Command string: A shell command to execute.
  • Command array: An array where the first element is the command and the rest are arguments.
json
{
  "tasks": {
    "taskName": "command to run",
    "build": ["deno", "run", "--allow-read", "build_script.ts"]
  }
}
๐Ÿ’ป

Example

This example shows a deno.json file defining two tasks: start to run a server script and test to run tests. You can run them with deno task start or deno task test.

json
{
  "tasks": {
    "start": "deno run --allow-net server.ts",
    "test": ["deno", "test", "--allow-read"]
  }
}
Output
Running task: start > deno run --allow-net server.ts Running task: test > deno test --allow-read
โš ๏ธ

Common Pitfalls

Common mistakes when defining tasks include:

  • Using invalid JSON syntax (missing commas or quotes).
  • Defining commands as arrays but mixing string and array formats incorrectly.
  • Forgetting to run tasks with deno task <task-name>.
  • Not granting required permissions in commands, causing runtime errors.

Always validate your deno.json file and test tasks individually.

json
Wrong:
{
  "tasks": {
    "build": "deno run build.ts",  // Missing comma here fixed
    "test": ["deno", "test"]
  }
}

Right:
{
  "tasks": {
    "build": "deno run build.ts",
    "test": ["deno", "test"]
  }
}
๐Ÿ“Š

Quick Reference

PropertyDescriptionExample
tasksObject defining named tasks"tasks": { "start": "deno run app.ts" }
Task nameKey used to run the task"start"
Command stringShell command to execute"deno run --allow-net server.ts"
Command arrayCommand and arguments as array["deno", "test", "--allow-read"]
Run taskCLI command to run task`deno task start`
โœ…

Key Takeaways

Define tasks inside the "tasks" object in deno.json as command strings or arrays.
Run tasks using the CLI command: deno task .
Ensure JSON syntax is correct to avoid errors.
Use arrays for commands with multiple arguments for clarity.
Grant necessary permissions in commands to prevent runtime failures.