Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize file right click actions on Visual Studio Code?

I need to execute a JS code on a json file when I right click on it using VSCode and show the result on a modal or on command prompt based on other code.

For example:

Code to execute (example.js) when right-clicking a json file:

function run(fileLocation){
   var file = require('./'+fileLocation);
   return file.length;
}

The example.json (file to be right-clicked):

[{id: a},{id: b},{id: c},{id: d},{id: e}]

Like the image below, it would appear on the menu like Execute example.js or something like this.

Add code to right click actions on VS Code

Is there a way to do it?

like image 802
spaceman Avatar asked Sep 12 '25 13:09

spaceman


1 Answers

For this, you'll need two contributions:

  • A command contribution your package.json that defines some basic info about the command. You'll also need a command registration in your source code that implements the command.

  • A menu contribution in the package.json for explorer/context. This should be linked to the command you defined.

All together, this would look something like:

// package.json

"activationEvents": [
    "onCommand:extension.doThing"
],
"contributes": {
    "commands": [{
        "command": "extension.doThing",
        "title": "Do the thing",
        "category": "My Extension"
    }],
    "menus": {
        "editor/title": [{
            "command": "extension.doThing",
            "group": "navigation"
        }]
    }
}

// in your extension source

import * as vscode from 'vscode';

vscode.commands.registerCommand('extension.doThing', (resource: vscode.Uri) => {
    ...
})
like image 97
Matt Bierner Avatar answered Sep 14 '25 07:09

Matt Bierner