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
.
found this article which talks about similar approach