Visual Studio Code Run task on save
In Visual Studio Code, you can configure tasks to run automatically when you save a file using the tasks.json file.
Here is a step-by-step guide for configuring tasks to run on save:
Method 1: Using plugin Trigger Task on Save
You can use the Trigger Task on Save extension.
Configure plugin settings
To set it up, add the following to your .vscode/settings.json
:
{
"task.saveBeforeRun":"always",
// task name to run on save action
"triggerTaskOnSave.selectedTask":"bootRun",
// enable plugin
"triggerTaskOnSave.on":true,
// restart task when running
"triggerTaskOnSave.restart":true,
// run in background
"triggerTaskOnSave.showNotifications":false,
// run in background
"triggerTaskOnSave.showStatusBarToggle":false,
"triggerTaskOnSave.tasks":{
"build":[
// watch file patterns
"server/**/*.html",
"jvm/**/*.java",
"server/**/*.java"
]
}
}
Configure tasks.json
{
"version": "2.0.0",
"tasks": [
{
// run in background
"isBackground": true,
// task name
"label": "bootRun",
"type": "shell",
// command shell to run
"command": "gradlew bootRun",
"args": [],
"group": {
"kind": "build",
"isDefault": true
},
// task description
"detail": "run gradle bootRun",
"presentation": {
// run in background
"reveal": "silent",
"panel": "shared"
},
"problemMatcher": [],
"options": {
// working directory
"cwd": "${workspaceFolder}"
},
"runOptions": {
"runOn": "default"
}
}
]
}
Method 2: Using default tasks.json
-
Open your project in Visual Studio Code.
-
Press
Ctrl + Shift + B
(Windows/Linux) orCmd + Shift + B
(Mac) to open the “Run Build Task” menu. -
Select “Configure Build Task” and then choose the type of task you want to create (e.g., “Create tasks.json file from template”).
-
Choose the appropriate template based on your project (e.g., “Others”).
-
Modify the generated “tasks.json” file to include a task that runs on save. For example:
{
"version": "2.0.0",
"tasks": [
{
"label": "Run On Save",
"type": "shell",
"command": "your_command_here",
"group": {
"kind": "build",
"isDefault": true
},
"presentation": {
"reveal": "always",
"panel": "new"
},
"runOptions": {
"runOn": "save"
}
}
]
}
Replace “your_command_here” with the actual command you want to run. Make sure the command is something that can be executed from the command line.
Note: option “runOn”: “save” triggers the execution of the task when the file is saved.
Make sure the task is properly configured for your project and that the necessary tools are installed.
"runOptions": {
"runOn": "save"
}
- Save the “tasks.json” file.
Conclusion
Now, when you save a file in your project, the specified task will be executed automatically.
The two tricks above worked when I tested previously. That’s the article about Run task on save using VSCode (Visual Studio Code)