Automatic Node.js Version - The Easy Way

Learn how to configure your Zsh shell to automatically switch to the correct Node.js version using NVM and a project’s .nvmrc file.

If you’re using nvm, you can add the following script to the end of your .zshrc file to ensure that the appropriate Node.js version is installed and activated whenever you navigate into a project directory containing an .nvmrc file.

# Automatically use the Node.js version defined in .nvmrc (if it exists)
autoload -U add-zsh-hook

# Installs the relevant node version
load-nvmrc() {
  if [[ -f .nvmrc && -r .nvmrc ]]; then
    local nvmrc_node_version=$(<.nvmrc)
    if [[ "$(nvm version)" != "v${nvmrc_node_version}" ]]; then
      nvm use || nvm install
    fi
  fi
}

add-zsh-hook chpwd load-nvmrc
load-nvmrc