DEV Community

rinkevich
rinkevich

Posted on Edited on

Speeding up NVM for zsh

Just replace your default loader with this snippet in your .zshrc.

Idea is to postpone initialisation until you enter a directory that contains .nvmrc file.

# NVM
export NVM_DIR="$HOME/.nvm"

# Add any Node version for powerlevel10k to be less noisy
# export PATH="$HOME/.nvm/versions/node/v14.15.5/bin:$PATH"
#[ -s "$(brew --prefix nvm)/nvm.sh" ] && . "$(brew --prefix nvm)/nvm.sh"  # This loads nvm

# Based on official autoload for ZSH https://github.com/nvm-sh/nvm#zsh
autoload -U add-zsh-hook
load-nvmrc() {
  if [ -f ".nvmrc" ]; then
    if ! typeset -f nvm_find_nvmrc > /dev/null; then 
      [ -s "$(brew --prefix nvm)/nvm.sh" ] && . "$(brew --prefix nvm)/nvm.sh" --no-use 
    fi

    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
    elif [ "$node_version" != "$(nvm version default)" ]; then
      echo "Reverting to nvm default version"
      nvm use default
    fi
  fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc
Enter fullscreen mode Exit fullscreen mode

Top comments (0)