In VS Code, it's possible to create a build task (or test task) to run a terminal command (i.e. a shell command, a command-line) using tasks.json
. An example:
{
"version": "2.0.0",
"tasks": [
{
"label": "build-tsc-and-sass",
"detail": "Runs Typescript and Sass compilers.",
"type": "shell",
"command": "npx tsc && npx sass style.css ../dist/style.scss",
"options": {
"cwd": "${workspaceFolder}/src/"
},
"group": {
"kind": "build",
"isDefault": true
},
},
]
}
Understanding the Code
The label
and detail
keys are just random text we can use to identify and describe our task.
The type = shell
key-value pair tells VS Code this task is a terminal command task, and command
tells VS Code what command to run.
In this example, the command we're running simply runs npx tsc
(the Typescript compiler) and then npx sass
(the Sass compiler) if the Typescript compiler succeeds. In other words, we're running both tasks in series, one after the other.
The cwd
option tells VS Code to use a change the Current Working Directory before running the command. It's like calling cd src
before the command. The text code ${workspaceFolder}
will be replaced by the filepath to the current workspace.
Observation: originally, VS Code could only open one folder as a workspace. Nowadays, you can have "multi-root" workspaces (one workspace with multiple folders open). In this case, you're going to have one tasks.json
per "folder." You don't have to worry about this if you don't use this multi-root feature, but which tasks are available depends on which root folder is currently opened in the side pane.
The isDefault
option makes this task the default build task, so you can run it with the keyboard shortcut Ctrl+Shift+B. If this isn't intended, you can remove it.
The kind
option tells VS Code what kind of task it is. Valid values are build
, test
, or none
. This seems to have no purpose except letting VS Code filter which tasks to display in its GUI when you use "Run Build Task..." from the menubar without a default build task.
Leave a Reply