skip to Main Content

I want to run npm run start when I press F5, but only when the file, package.json exists in the root of the project (i.e. when the folder open is a Node.js project).

To illustrate what I’m trying to do, let’s pretend that file.exists package.json does what I want it to (which it doesn’t).

~/.config/Code/User/keybindings.json:

[
  {
    "key": "f5",
    "command": "workbench.action.terminal.sendSequence",
    "args": {
        "text": "npm run startr"
    },
    "when": "file.exists package.json"
  },
]

What is the correct way to do this? I can’t see anything related to testing if a file exists in the docs.

2

Answers


  1. Chosen as BEST ANSWER

    Based on rioV8's answer, I expanded upon the solution by showing the terminal:

      {
        "key": "f5",
        "command": "runCommands",
        "args": {
          "commands": [
            "workbench.action.terminal.focus",
            {
              // depends on: https://marketplace.visualstudio.com/items?itemName=rioj7.command-variable
              "command": "extension.commandvariable.inTerminal",
              "args": {
                "command": "extension.commandvariable.transform",
                "args": { "text": "npm run start" },
                "addCR": true,
                "when": "file.exists ${workspaceFolder}${pathSeparator}package.json"
              }
            }
          ]
        },
      },
    

  2. You can use the extension Command Variable v1.55.0 and the command extension.commandvariable.inTerminal

      {
        "key": "f5",
        "command": "extension.commandvariable.inTerminal",
        "args": {
          "command": "extension.commandvariable.transform",
          "args": { "text": "npm run start" },
          "addCR": true,
          "when": "file.exists ${workspaceFolder}${pathSeparator}package.json"
        }
      }
    

    The keybinding will always execute. The when test is performed in the command not before the command execution. If you use F5 then you lose the default launch functionality.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search