Search code examples
npmvisual-studio-codekey-bindings

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.


Solution

  • 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 tasks.json format documentation for reference

    {
        "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