4

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?

Mark
  • 143,421
  • 24
  • 428
  • 436
spaceman
  • 659
  • 2
  • 11
  • 29

1 Answers1

7

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) => {
    ...
})
Matt Bierner
  • 58,117
  • 21
  • 175
  • 206
  • 1
    If you want your menu item to appear in the context of the Explorer then use "explorer/context", instead of "editor/title" – Six80 Aug 11 '21 at 03:13