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
.
An alternative solution I've found that appears to work well is installing this extension https://marketplace.visualstudio.com/items?itemName=Orta.vscode-jest and specifying the version of node you wish to use in the vscode.json using, for example:
The above sources the nvm setup script, sets the version and runs the test command.