Skip to content

Instantly share code, notes, and snippets.

@rofrol
Forked from fvclaus/README.md
Created October 25, 2021 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rofrol/e851f54813bbde1ffae7bf2583752fce to your computer and use it in GitHub Desktop.
Save rofrol/e851f54813bbde1ffae7bf2583752fce to your computer and use it in GitHub Desktop.
Run vscode tasks with nvm

Nvm does not work in vscode tasks, because tasks are run without a shell. .bashrc is not loaded and the nvm command is unknown.

My solution uses a wrapper script around /bin/bash that reads in the correct node version from .npmrc in the project folder.

#!/bin/bash

set -e

if [[ "$2" == nvm* ]]; then
    export NODE_VERSION=v$(cat .nvmrc)
    if [ -z "$NODE_VERSION" ]; then
        echo "$(pwd)/.nvmrc does not exist or is empty"
        exit 1
    fi
    CLEAN_CMD=$(echo $2 | sed -e 's/nvm/npm/g')

    /bin/bash -c "~/.nvm/nvm-exec $CLEAN_CMD"
else
    /bin/bash -c $@
fi

The wrapper script is configured as default shell using the terminal.integrated.automationShell.<os> setting in settings.json.

Example:

    "terminal.integrated.automationShell.linux": "<path>/nvm-shell.sh"

Instead of defining a tasks of type npm, the shell type is used instead:

    {
        "type": "shell",
        "command": "nvm run compile",
        "label": "npm-compile",            
        "problemMatcher": "$tsc",
        "isBackground": false,  
        "presentation": {
            "reveal": "always"
        },
        "group": {
            "kind": "build",
            "isDefault": true
        }
    }

Theoretically, it should be possible to configure this script per taks without the global configuration:

        "linux": {
            "options": {
                "shell": {
                    "executable": "<path>/nvm-shell.sh",
                    "args": []
                }
            }
        }

But that always returns an error 127 command nvm not found.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment