VS Code - How to write tasks.json to run multiple commands in a single task

Viewed 5548

I'm new to Visual Studio Code and trying to write tasks.json to perform my custom build task so that I can build my project by "Terminal / Run Build Task ...".

However, my build task is composed of multiple commands, like (windows script for example):

preBuildTask1.bat
preBuildTask2.bat
...
build.bat
...
postBuildTask1.bat
postBuildTask2.bat
...

I looks like task.json only allows me to put a single command for "command" property, like:

    "tasks": [
        {
            "label": "emcc",
            "type": "shell",
            "command": "buildTask.ps1",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        },
    ]
}

My current work around is put all sub-tasks in a powershell script then invoke that script in tasks.json, like "buildTask.ps1" showed in the code above. It will be more convenient if I can directly write multiple tasks for a single command property. Anyone knows how to do that? Thanks.

1 Answers

Thanks for the suggestions from Mark, I find the solution to define a command with multiple sub-tasks in tasks.json of VS code:

Solution 1: Simply put all tasks in the command value, separated by ";":

"command": "task1;task2;task3"

Solution 2: Define sub-task as environment variables, then invoke them one by one. For example, on Windows, we can use powershell's command Invoke-Expression:

First, define all sub-tasks as environment variables:

"options": {
        "env": {
                "TASK_1": "emsdk_env",
                "TASK_2": "emcc canvas.cpp -o canvas.html --shell-file canvas_shell.html -s NO_EXIT_RUNTIME=1 -s EXTRA_EXPORTED_RUNTIME_METHODS='[\"ccall\", \"cwrap\"]'",
                "TASK_3": "http-server -p 8000"
            }
    },    

Then, invoke them:

  "tasks": [
        {
            "label": "emcc",
            "type": "shell",
            "command": "Invoke-Expression $env:TASK_1; Invoke-Expression $env:TASK_2; Invoke-Expression $env:TASK_3",
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": []
        }
    ]

The second solution is useful when sub-task command lines are very long and do not want write a super long string when defining command.

Of course, we can also create a single script then invoke it, which is my original solution.

Related