How to automate switching Node.js versions with nvm and zsh
About 1 min reading time
Prerequisites
Before we dive in, you'll need to have the following installed on your machine:
- zsh
- nvm (Node Version Manager)
If you don't have nvm installed, you can find instructions on the nvm GitHub page.
Setting up auto-switching
Assuming you have nvm and Zsh installed, here's how to set up auto-switching:
In the root directory of your project, create a
.nvmrc
file and add the version of Node.js you want to use. For example, if your project requires Node.js version 18.15.0, add 18.15.0 to the.nvmrc
file.Open your
.zshrc
file in your favorite text editor (e.g.vim ~/.zshrc
).Add the following lines at the end of the
.zshrc
file:
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
Save and close the
.zshrc
file.Restart your terminal or run source
~/.zshrc
for the changes to take effect.
That's it! Now, whenever you enter your project's directory, the zsh-hook we defined in your ~/.zshrc
file will automatically switch to the Node.js version specified in the project's .nvmrc
file. This ensures that you are always using the correct version of Node.js for your project without needing to manually switch versions every time you enter the directory. In every other directory this will switch to your default Node.js version.
I hope this post has been helpful. If you know a better alternative, please reach out to me on Mastodon. Happy coding!