在VS代码中运行终端命令的快捷方式

问题描述 投票:2回答:2

有没有办法在终端中运行特定命令的热键?假设我想通过热键编译我的TypeScript文件,而不是键入终端“tsc”或该命令的任何其他变体。 (编辑:我知道可以在保存时重新编译TS,但问题仍然是相同的)

terminal visual-studio-code
2个回答
7
投票

通常,您将设置构建或其他任务或npm脚本,然后使用热键触发该脚本。使用send text to the terminal还有另一种新方法。

例如,在你的键绑定中尝试这个:

{
    "key": "ctrl+alt+u",
    "command": "workbench.action.terminal.sendSequence",
    "args": {
      "text": "node -v\u000D"
    }
}

或者对于npm脚本:

 {
    "key": "ctrl+alt+u",
    "command": "workbench.action.terminal.sendSequence",
    "args": {
      "text": "npm run-script test\u000D"
    }
 }

这将运行node -v命令(\u000D是一个返回,所以它运行)。我仍然建议实际设置构建任务,然后有用于运行构建任务的键盘:Ctrl-shift-B。或者是一个npm脚本。

例如,如果要运行更复杂的脚本,请参阅how to bind a task to a keybindinghow to keybind an external command


编辑:从v1.32开始,您现在可以执行以下操作:

{
  "key": "ctrl+shift+t",
  "command": "workbench.action.terminal.sendSequence",
  "args": { "text": "tsc '${file}'\u000D" }
}

现在,您可以在键绑定中使用内置变量(如${file})和sendSequence命令。我用单引号包装${file},以防你的目录结构有一个名称中有空格的文件夹。而\u000D是一个回报。


2
投票

我不认为默认情况下vscode可以执行此操作,但您可以尝试此扩展。这对我有用。

https://marketplace.visualstudio.com/items?itemName=mkloubert.vs-script-commands


1
投票

您可以使用VSCode tasks完成此操作,然后将任务连接到键绑定。这种方法的缺点是你必须在你的工作区tasks.json文件夹中有一个.vscode文件(它不能是全局的)。

这是一个我想在自定义GitHub远程中打开文件的示例:

// tasks.json
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Open in remote",
            "type": "shell",
            "command": "open https://github.custom.com/org/repo/blob/master/${relativeFile}#L${lineNumber}"
        }
    ]
}

// keybindings.json
{
    "key": "ctrl+o",
    "command": "workbench.action.tasks.runTask",
    "args": "Open in remote"
},

如果你很好奇,可以使用以下一些VS Code变量:https://code.visualstudio.com/docs/editor/variables-reference

这里有一个长期存在的问题,如果没有任务,这应该更容易做到:https://github.com/microsoft/vscode/issues/871

© www.soinside.com 2019 - 2024. All rights reserved.