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

时间:2018-10-12 19:38:19

标签: terminal visual-studio-code

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

4 个答案:

答案 0 :(得分: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是回报。

答案 1 :(得分:2)

我认为默认情况下vscode不能做到这一点,但是您可以尝试此扩展。那对我有用。

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

答案 2 :(得分: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

答案 3 :(得分:1)

除了@mark ..

"args": { "text": "npm run-script test | tee /dev/null \u000D" }

这样,它将运行包括bash脚本在内的任何脚本,这些脚本不会与它们的参数冲突 (例如,尝试不带T恤的rsync)