Using VS Code Tasks with Go

From the VS Code Tasks documentation:

Tasks in VS Code can be configured to run scripts and start processes so that . . . existing tools can be used from within VS Code without having to enter a command line or write new code. Workspace or folder specific tasks are configured from the tasks.json file in the .vscode folder for a workspace.

To begin configuring tasks, run the Tasks: Configure Task command from the Command Palette (Ctrl+Shift+P).

This will create a tasks.json file in your workspace’s .vscode folder.

Replace the contents of this file with the following and adjust the tasks as needed.

  1. {
  2. "version": "2.0.0",
  3. "type": "shell",
  4. "command": "go",
  5. "cwd": "${workspaceFolder}",
  6. "tasks": [
  7. {
  8. "label": "install",
  9. "args": ["install", "-v", "./..."],
  10. "group": "build",
  11. },
  12. {
  13. "label": "run",
  14. "args": ["run", "${file}"],
  15. "group": "build",
  16. },
  17. {
  18. "label": "test",
  19. "args": ["test", "-v", "./..."],
  20. "group": "test",
  21. },
  22. ],
  23. }

You can run these tasks via the Tasks: Run Task command or by using the Ctrl+Shift+B shortcut.

You can also define additional tasks to run other commands, like go generate. Here’s an example of a task to run only a specific test (MyTestFunction, in this case):

  1. {
  2. "label": "MyTestFunction",
  3. "args": [ "test", "./...", "-test.run", "MyTestFunction"]
  4. }

If you want to invoke tools other than go, you will have to move the "command": "go" setting into the task objects. For example:

  1. {
  2. "version": "2.0.0",
  3. "cwd": "${workspaceFolder}",
  4. "tasks": [
  5. {
  6. "label": "install",
  7. "command": "go",
  8. "args": ["install", "-v", "./..."],
  9. "group": "build",
  10. "type": "shell",
  11. },
  12. {
  13. "label": "run",
  14. "command": "go",
  15. "args": ["run", "${file}"],
  16. "group": "build",
  17. "type": "shell",
  18. },
  19. {
  20. "label": "test",
  21. "command": "go",
  22. "args": ["test", "-v", "./..."],
  23. "group": "test",
  24. "type": "shell",
  25. },
  26. ],
  27. }

Learn more by reading the VS Code Tasks documentation.