Automatic version switch for NVM

14 de septiembre del 2016 鈥 425 palabras 鈥 2 min

If you鈥檙e using multiple versions for each of your projects, you might use the nvm use command every time you need to switch. This gets old very fast and nvm doesn鈥檛 have a native solution for this problem.

The NVM documentation has a dedicated section for this. You can go and read them there or continue reading for a curated version.

Manual Switch

The manual switch involves a file called .nvmrc in your project鈥檚 directory.

echo "5.9" > .nvmrc
echo "lts/*" > .nvmrc # to default to the latest LTS version

In order to switch, you鈥檒l need to run nvm use but if you cd outside of the directory, the version is not going to switch back to your default.

Pros

Cons

Automatic Switch

The automatic switch will switch your node version automatically when you cd into a project folder that contains the .nvmrc file. You鈥檒l need to have zsh as a shell to make this work.

Add the following content at the end of your .zshrc file, after the nvm initialization.

# place this after nvm initialization!
autoload -U add-zsh-hook
load-nvmrc() {
  if [[ -f .nvmrc && -r .nvmrc ]]; then
    nvm use
  elif [[ $(nvm version) != $(nvm version default)  ]]; then
    echo "Reverting to nvm default version"
    nvm use default
  fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc

Now every time you cd into a directory you鈥檒l switch to the project version if it has the .nvmrc inside with a valid version.

If you go out of the directory or cd into a directory that doesn鈥檛 have the version file, your shell will use the default one in your system.

Pros

Cons

That鈥檚 it for now, please add in the comments if you鈥檙e familiar with another solution.