Skip to content

Instantly share code, notes, and snippets.

@rafaellucio
Last active August 14, 2024 17:33
Show Gist options
  • Save rafaellucio/208c18a2274bdd71671893540ce7134c to your computer and use it in GitHub Desktop.
Save rafaellucio/208c18a2274bdd71671893540ce7134c to your computer and use it in GitHub Desktop.
Plugin NVM oh-my-zsh

NVM plugin

Description

This plugin provides load nvm if it exists and when the .nvmrc file exists in your directory, it will download the described node version.

To start using it:

  • Add the ZSH_NVM_AUTOLOAD=true at the beginning of the file ~/.zshrc
  • Add nvm plugin to your plugins array in ~/.zshrc
ZSH_NVM_AUTOLOAD=true
# ...
plugins=(... nvm)
# Set NVM_DIR if it isn't already defined
[[ -z "$NVM_DIR" ]] && export NVM_DIR="$HOME/.nvm"
# Load nvm if it exists
[[ -f "$NVM_DIR/nvm.sh" ]] && source "$NVM_DIR/nvm.sh"
# Auto load version node if exists .nvmrc
[[ -n "$ZSH_NVM_AUTOLOAD" ]] || ZSH_NVM_AUTOLOAD=false
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
fi
if [ "$nvmrc_node_version" != "$node_version" ]
then
nvm use
fi
elif [ "$node_version" != "$(nvm version default)" ]
then
echo "Reverting to nvm default version"
nvm use default
fi
}
if [[ "$ZSH_NVM_AUTOLOAD" == "true" ]]
then
autoload -U add-zsh-hook
add-zsh-hook chpwd load-nvmrc
load-nvmrc
fi
@cordosvictor
Copy link

cordosvictor commented Jun 23, 2022

Thanks! Works exactly as expected!

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