如何在 Visual Studio Code 上自定义文件右键单击操作?

spa*_*man 1 visual-studio-code vscode-extensions

json当我使用 VSCode 右键单击​​文件并在基于其他代码的模式或命令提示符上显示结果时,我需要在文件上执行 JS代码。

例如:

右键单击 json 文件时要执行的代码 (example.js):

function run(fileLocation){
   var file = require('./'+fileLocation);
   return file.length;
}
Run Code Online (Sandbox Code Playgroud)

example.json(要右键单击的文件):

[{id: a},{id: b},{id: c},{id: d},{id: e}]
Run Code Online (Sandbox Code Playgroud)

像下图一样,它会出现在菜单上,Execute example.js就像这样。

将代码添加到 VS Code 上的右键单击操作

有没有办法做到这一点?

Mat*_*ner 5

为此,您需要两个贡献:

  • 一个命令贡献你的 package.json,它定义了关于命令的一些基本信息。您还需要在实现命令的源代码中进行命令注册。

  • 一个菜单的贡献package.jsonexplorer/context。这应该链接到您定义的命令。

总之,这看起来像:

// 包.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"
        }]
    }
}
Run Code Online (Sandbox Code Playgroud)

// 在你的扩展源中

import * as vscode from 'vscode';

vscode.commands.registerCommand('extension.doThing', (resource: vscode.Uri) => {
    ...
})
Run Code Online (Sandbox Code Playgroud)