Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run npm command on keybinding in Visual Studio Code

I want to bundle js files on save using webpack.

This is best accomplished using webpack watch. But whatever...

In the answers below is the result of my googling, which I hope will be useful to somebody at some point.

like image 814
Rafael Emshoff Avatar asked Jan 30 '17 20:01

Rafael Emshoff


People also ask

How do I add a Keybinding in VS Code?

You can do that in the Preferences -> Keyboard Shortcuts section. Search for "Run Python File in Terminal", select the command and press the little + sign on the left.

Why NPM is not working in VS Code?

If you're calling npm from the VSCode terminal, you need to restart VSCode first before trying again. If you still get the error, then try restarting your computer first. The error should be gone after you restart. Now you should be able to install any npm package to your local computer with npm install command.

How do I run a shortcut key in Visual Studio?

In VS Code, you only need to use a shortcut to run your code. That shortcut is Ctrl + Alt + N. There are a few more ways to run code. Pressing F1 and then choosing “Run Code” also works.


2 Answers

Use npm to run webpack bundling on save in VSC ... or any other npm command you like, like compiling typescript.

Add a .vscode/tasks.json to your project:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "command": "npm",
    "isShellCommand": true,
    "showOutput": "never",
    "suppressTaskName": true,
    "tasks": [
        {
            "taskName": "bundle",
            "args": ["run", "bundle"],
            "isBuildCommand": true,
            "showOutput": "never"
        }
    ]
}

Edit keybindings.json (File>Preferences>Keyboard Shortcuts).

// Place your key bindings in this file to overwrite the defaults
[
    {
        "key" : "ctrl+s",
        "command" : "workbench.action.tasks.build"
    }
]

The workbench.action.tasks.build is a built-in vsc hook. See here: https://code.visualstudio.com/docs/customization/keybindings#_tasks

The task can also be accessed in VSC via

  1. Ctrl+P
  2. Type task + space
  3. See your task suggested or continue typing it's name
like image 200
Rafael Emshoff Avatar answered Jan 03 '23 11:01

Rafael Emshoff


keybindings.json

{
    "key": "ctrl+shift+alt+b",
    "command": "workbench.action.terminal.sendSequence",
    "args": {
        "text": "npm run test\r"
    },
},
like image 34
Alex Avatar answered Jan 03 '23 10:01

Alex