Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build currently opened file in Visual Studio Code

I have a workspace that I use for smaller test programs I write to practice concepts. Hence, in VS Code, I have a build task for each file in the folder.

By default, VS Code builds the task with the "isDefault": true, flag. Ideally, I would like to figure out a way for me to build the currently opened file, so that when I switch files I am editing, I do not need to manually reset the flag to the build task I want to use.

To my knowledge, the VS Code Tasks Documentation doen't provide a solution. There must be a way to accomplish this without manually adjusting the flag. Any help is appreciated.

like image 727
ifconfig Avatar asked Aug 14 '17 16:08

ifconfig


People also ask

How do I see open files in VS Code?

Quick file navigation# VS Code provides two powerful commands to navigate in and across files with easy-to-use key bindings. Hold Ctrl and press Tab to view a list of all files open in an editor group. To open one of these files, use Tab again to pick the file you want to navigate to, then release Ctrl to open it.

How do I run a current file in Visual Studio?

In the simplest case, to build and run an open project in Visual Studio: Press F5, choose Debug > Start with debugging from the Visual Studio menu, or select the green Start arrow and project name on the Visual Studio toolbar.

What is Zen mode in VS Code?

Zen mode is a feature in a VS Code that hides all UI (Status Bar, Activity Bar, Panel, and Sidebar) and displays only the editor on a full screen. Zen Mode.


2 Answers

You can use the ${file} wildcard to pass the current file to your build program/script.

There's an example given in the docs for TS: https://code.visualstudio.com/Docs/editor/tasks#_operating-system-specific-properties

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "presentation": {
        "panel": "new"
    },
    "tasks": [
        {
            "taskName": "TS - Compile current file",
            "type": "shell",
            "command": "tsc ${file}",
            "problemMatcher": [
                "$tsc"
            ]
        }
    ]
}
like image 171
Rob Lourens Avatar answered Sep 18 '22 20:09

Rob Lourens


To Build on Rob's Answer, you can also set a shortcut key combination to trigger each task by adding to keybindings.json, e.g.

{
    "key": "ctrl+h",
    "command": "workbench.action.tasks.runTask",
    "args": "Run tests"
}

where the args component is replaced with the task name.

You could use this in combination with ${file} in tasks.json to differentiate between the separate build types.

e.g. hit Ctrl+h for python and Ctrl+Shift+h for tsc

like image 31
jdow Avatar answered Sep 17 '22 20:09

jdow