DEV Community

Lana Kushnir
Lana Kushnir

Posted on

2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site