Shing Wong

Shing Wong

Simplify Node Version Repo Switching

Holy shit. It's been over 3 years since I've had this portfolio site up, which I've kind of forgot about, but kind of didn't. Anyhow, lately I've had a sudden craving to blog. Maybe, it's because I've recently had a child and secretly want a space for my future kids to read my blog. Maybe, I'm just getting old and it helps me remember things. Maybe, I'm finally blogging because it's something I've always wanted to do, but too afraid to?

Anyways, it doesn't really matter. Thank you for listening to my rant, now let's get straight to the real post.

Recently, I got a new device and I pulled an old project from Github. So, I did the usual npm i etc... and to my surprise I realized I was getting compilation errors. Ultimately, it was caused by a nodejs version discrepancy. My newly setup environment was on v18 and a dependency on this old project was limited to v16.

With that said, as the number of projects you work on grows, it becomes more cumbersome to keep track of and switching version is rather redundant. So, I recently wrote a script to auto switch nodejs version depending on a .nvmrc file within the root directory of a project.

#!/bin/zsh

# This script appends a shell function to .zshrc config file. The function checks current directory for .nvmrc file and if found auto runs `nvm use` to switch to pinned node version.

# Defines the function "load-nvmrc()"
# Gets current version of Nodejs stores into variable called `node_version`
# Searches for .nvmrc in current dir and parent dir using `nvm_find_nvmrc` command, then stores path to `nvmrc_path`
# If `.nvmrc` file is found, get Node version from file using `cat` and `nvm version` cmd and stores local variable called `nvmrc_node_version`
# If `nvmrc_node_version` is not available, install version specificed in `.nvmrc`with `nvm install` cmd
# If `nvmrc_node_version` is available and not the same as node_version, switch to specified version in `.nvmrc` file by using `nvm use`
# if `.nvmrc` file is not found, but `node_version` is not same as default version in nvm, switch to default version of Node with `nvm use default` cmd

echo "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" >> ~/.zshrc