Getting Started: Prerequisite Tooling

Tags
Owner
Brian Kuperman
Verification

Prerequisites

Automatic Node Version Switching

Projects often times require a specific version of node to run properly. Node versions can be easily managed with the use of NVM. Once NVM is installed you can switch node versions by using the nvm command, for example nvm use 16 will load node v16 into your current shell.

Taking this a stwwep further we can create a .nvmrc in the root of our projects and inside the contents of the file is simply the node version you want to use for that project. For example v18.16.0. Then a developer can simply run the nvm use command to source the correct node version.

A script can be added to your zsh profile which will automatically check to see if there is a .nvmrc file in your current directory and switch to the correct node version. To add this script follow these steps:

  1. In a terminal window run nano ~/.zshrc
  2. At the end of the file add the following:
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