When using nvm, one can run nvm use
and if the project has a .nvmrc file in it – the version of node specified there will be set in your browser. However, on many of the projects I work on there is no .nvmrc
file but the package.json
file does contain an engines
section and in that section it specifies the preferred version of node (just like .nvmrc
would). e.g.
...
"engines": {
"node": "12",
"npm": "6"
},
...
While I could lookup the value in package.json
and then run nvm use
with that version (e.g. nvm use 12
), instead I can use jq with nvm
to do the lookup and set the version.
nvm use $(jq -r '.engines.node' package.json)
Shell Alias
Instead of trying to remember this command you we can setup an alias for this command. I like nvmpe
for “nvm” + “p”ackage.json + “e”ngine.
e.g.
alias nvmpe='nvm use $(jq -r ".engines.node" package.json)'
Shell Function
If we want to add checks that both the nvm
and jq
commands are installed on the system and we have a package.json
with an .engines.node
entry, we could make this a shell function (we should be able to add these same checks with an alias but I’ll leave that as an exercise for the reader).
# See https://salferrarello.com/jq-nvm-set-node-version/ for explanation.
function nvmpe() {
if ! command -v nvm &> /dev/null
then
echo "This command requires nvm"
echo "See https://github.com/nvm-sh/nvm"
return 1
fi
if ! command -v jq &> /dev/null
then
echo "This command require jq"
echo "See https://stedolan.github.io/jq/"
return 1
fi
if [[ ! -r package.json ]]
then
echo 'Can not read package.json in this directory'
return 1
fi
node_ver=$(jq -r '.engines.node' package.json)
if [[ $node_ver -eq '' ]]
then
echo "package.json does not contain an .engines.node entry"
return 1
fi
# Set node version.
nvm use $node_ver
}
Leave a Reply