Is there a way to run a command with VS Code tasks?
Asked Answered
A

1

13

In VS Code, I have an extension whose commands I can run by pressing F1 and searching by name. However I would like to automatically run it from a task (tasks.json). I know its full name from keyboard shortcuts.

Amandie answered 29/1, 2018 at 21:28 Comment(0)
U
4

You can run a valid command in tasks.json with the ${command:} syntax:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "echo",
            "command": "${command:editor.action.addCommentLine}",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

The above example comments out the current line

Compound Commands

If you would like to run commands sequentially/parallel, you can use the dependsOn property to run multiple commands:

Either a string representing another task or an array of other tasks that this task depends on.

For example, let's say there's a scenario where you want to duplicate the current line you are on down, comment it out above, and arbitrarily, for demonstration purposes, focus the terminal immediately:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "create temporary duplicate line",
            "command": "${command:workbench.action.terminal.focus}",
            "dependsOn": [
                "duplicate line up",
                "comment line out"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        },
        {
            "label": "comment line out",
            "command": "${command:editor.action.addCommentLine}"
        },
        {
            "label": "duplicate line up",
            "command": "${command:editor.action.copyLinesUpAction}"
        }
    ]
}

Let's say the line you duplicated was:

<div></div>

The task would run and make this:

<!-- <div></div> -->
<div></div>

And then focus on the integrated terminal


You can review their documentation on command variables and other placeholder syntax, like taking in user input for creating dynamic tasks, or using the runOn property to automatically run a task on folder startup

Ume answered 29/7, 2020 at 1:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.