Node Version Manager

Introduction

Node Version Manager (nvm) is used to quickly switch between different Node.js versions. You should always prefer Docker over locally installed software, but for quick tests, nvm does the job pretty well.

Installation

Bash

See the official installation guide on the nvm repository.

Add the following to your .bash_profile or .bashrc:

enter_directory() {
if [[ $PWD == $PREV_PWD ]]; then
    return
fi

PREV_PWD=$PWD
if [[ -f ".nvmrc" ]]; then
    nvm use
    NVM_DIRTY=true
elif [[ $NVM_DIRTY = true ]]; then
    nvm use default
    NVM_DIRTY=false
fi
}

export PROMPT_COMMAND=enter_directory

This will automatically use the nvm version specified in a .nvmrc file.

To always install Yarn Classic, add the following to ~/default-packages:

yarn

Fish

See the official installation guide on the nvm repository.

Install fisher for fish package management:

curl https://git.io/fisher --create-dirs -sLo ~/.config/fish/functions/fisher.fish

Install bass for bash backwards compatibility:

fisher add edc/bass

Add the following files:

~/.config/fish/conf.d/nvm.fish

function nvm
   bass source ~/.nvm/nvm.sh --no-use ';' nvm $argv
end

~/.config/fish/conf.d/nvm.fish

function nvm_init --on-variable="PWD"
  set -l default_node_version (nvm version default)
  set -l node_version (nvm version)
  set -l nvmrc_path (nvm_find_nvmrc)
  if test -n "$nvmrc_path"
    set -l nvmrc_node_version (nvm version (cat $nvmrc_path))
    if test "$nvmrc_node_version" = "N/A"
      nvm install (cat $nvmrc_path)
    else if test nvmrc_node_version != node_version
      nvm use $nvmrc_node_version
    end
  else if test "$node_version" != "$default_node_version"
    echo "Reverting to default Node version"
    nvm use default
  end
end

function nvm_find_nvmrc
  bass source ~/.nvm/nvm.sh --no-use ';' nvm_find_nvmrc
end

nvm_init

This will automatically use the nvm version specified in a .nvmrc file.

To always install Yarn Classic, add the following to ~/default-packages:

yarn