Skip to content

Instantly share code, notes, and snippets.

@davisshaver
Created October 8, 2021 16:09
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 davisshaver/d94057a051e8bc263a13ecea1e9b3c33 to your computer and use it in GitHub Desktop.
Save davisshaver/d94057a051e8bc263a13ecea1e9b3c33 to your computer and use it in GitHub Desktop.
zsh nvm autoload
autoload -U add-zsh-hook
load-nvmrc() {
local node_version="$(nvm version)"
local nvmrc_path="$(nvm_find_nvmrc)"
if [ -n "$nvmrc_path" ]; then
local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")
if [ "$nvmrc_node_version" = "N/A" ]; then
nvm install
elif [ "$nvmrc_node_version" != "$node_version" ]; then
nvm use
fi
else
if ! command -v jq &> /dev/null
then
echo "This command requires jq"
echo "See https://stedolan.github.io/jq/"
echo "Reverting to nvm default version"
nvm use default
return 1
fi
if [[ ! -r package.json ]]
then
echo 'Can not read package.json in this directory'
echo "Reverting to nvm default version"
nvm use default
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"
echo "Reverting to nvm default version"
nvm use default
return 1
fi
nvm use $node_ver
fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment