DEV Community

Lana Kushnir
Lana Kushnir

Posted on

Automatically switching node versions |`nvm use`

Issue:
npm install or npm ci keeps throwing a ton of errors
Then I realize I am on a different version of node

Instead of remembering about it, checking if .nvmrc file exists, then switching to that node version, let nvm use do it all the work for you.

I use .zsh shell, so I used this script from nvm-sh#zsh docs

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

Result:
Blissss. I don't have to ever (hopefully) think about what version of node is currently used when I switch between projects.

Resources:
https://github.com/nvm-sh/nvm#zsh

Top comments (0)