Using Node Version Manager and .nvmrc to automatically switch Node versions per project
I use Node version manager (NVM) on OSX to manage multiple Node versions between projects.
NVM lets you run multiple versions of Node JS on your machine at once, and easily change between them. On the command line, you can see the versions of node available with nvm list
, and then use one with nvm use
(and the version no.).
So with this workflow setup, I change directory (cd
) into project folders, and immediately run node use XXX
(where XXX is the node version number) to change version.
Turns out there's a way to automate that. First, I use zsh to give my command line a bunch of nice extra features. You'll need zsh running to configure this correctly.
Configuring ZSH to recognize your .nvmrc file
With zsh installed, let's modify the .zshrc file (the file the stores all .zsh configuration) to do something when it sees a .nvmrc file.
In your CLI terminal of choice, edit .zshrc in nano by typing nano .zshrc
Now after the line that has configuration details for nvm, add the following:
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
Exit nano (ctrl + X, Y to save changes, and then hit enter). Close and reopen your terminal for the changes to take effect.
Adding the .nvmrc file
Now in a project that is running node, create a file called .nvmrc (in terminal, you can create a new file with the touch command, followed by the desired file name.
To set the project to use a specific version of node, simply add the version number, ie.
v9.11.1
Make sure you save the .nvmrc file.
Alternatively, if you just ant to use the most up-to-date version of node for your project, simple add
node -v > .nvmrc
Now, if you cd out of the folder, and back into it, you should see that nvm automatically runs the command to use the node version you specified.
Yay, automation!
Benefits of using .nvmrc file
This file can now be committed to version control, and tracked between team members, to ensure your team uses the same version of node. (ofcourse they'd have to make the .zshrc file changes themselves.
Conclusion
I found a few resources on the web that describe configuring .nvmrc files, but I had to rely on a bit of Googling, and piece together bits from a few links and threads to get the final result to work. Inspiration came from these great folks here, and here. Netlify's docs also have some info on .nvmrc here. They recommend using it to set your node version in their deployment pipeline.
Good stuff! ๐