NodeJS / JavaScript: Use NVM and .nvmrc to switch NodeJS versions automatically per project folder on Mac OS X

Your various software development projects are going to require you to use different versions of Node.js to compile and run; to make this process a little bit quicker, you can utilize NVM and .nvmrc files places in your project root folders to automatically switch versions when you change into them.

Let’s start by installing nvm using Brew:

brew install nvm

For those of us using Zsh as our Mac OS X shell, append the following to ~/.zshrc in your user home directory; it handles the automatic version switching per code project folder:

# If a .nvmrc file is present in the folder that we just changed into, switch to the version specified in it.
autoload -U add-zsh-hook
load-nvmrc() {
  local node_version="$(nvm version)"
  local nvmrc_path=".nvmrc"

  if [ -f "$nvmrc_path" ]; then
    local nvmrc_node_version=$(cat "$nvmrc_path")
    if [ "$nvmrc_node_version" != "$node_version" ]; then
      nvm use "$nvmrc_node_version"
    fi
  fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc

Next, you likely need to install a couple of different versions of Node.js; for example, to find the latest exact version of v18 to install, run:

nvm ls-remote 18

Now all we need to do is put a .nvmrc file in each project folder to switch to an installed version; if my ~/code/yllus_site/ folder needs version v18.20.8, a file at ~/code/yllus_site/.nvmrc should simply consist of:

 18.20.8 

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *