How to write a .nvmrc file which automatically change node version

As @Aditya-M-P has already mentioned you can run the following command inside your projects root directory to generate the .nvmrc to set a desired NodeJS version for you project to work properly:

node -v > .nvmrc

It will generate something like this inside your .nvmrc file:

v10.16.2

Also using 10.16.2 without the v letter will work just fine.

However, in the official documentation in the .nvmrc section it never mentions that once you get this file created, the specified node version will be loaded automatically. So that’s not enough, you need to run the command below so that nvm can look for the .nvmrc file to load the specified version:

nvm use

Here it is a gif for demoing purpose: 

To autoload the specified node version:

You need to add something else to your shell configuration depending on what you use bash or zsh

To get the exact configuration for each of them, please follow the instructions in the corresponding shell config section.

In my case I’m using zsh so I do need to add this at the end of my .zshrc file and here is the image that confirms it works like a charm:

# 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

I hope it could be useful for anyone else facing the same question! 😎

Leave a Comment