I need to have different versions of node/npm for different projects. I’d prefer to have each project “know” which version of node/npm it needs to use.
Before we get started, there are a few prerequisites:
- understand that this is a Mac solution. While I’m sure a similar solution exists for Windows, I am neither knowledgeable enough nor inclined to write a compatible shell script for Windows at this time.
- have/install nvm. I installed mine with Brew.
- have at least one version of node installed via nvm
- have a basic understanding of terminal.
- have a willingness to edit your .bash_profile.
Much like Ruby has a shortcut for setting the current version of Ruby to use, nvm has a similar feature. When you enter the following command…
… then nvm will look for a .nvmrc file and get the correct version number to use from there. So first navigate to a project folder that uses node and create a new file called .nvmrc. Inside just write 4.2. If you’re a command-line geek then do the following:
cd <project folder> touch .nvmrc # creates the file echo \4.2 >> .nvmrc # appends the version to the file cat .nvmrc # prints the file's contents
editing your .bash_profile
So the easiest way to make nvm read your .nvmrc file is to do a check when you change directories. We need to make a function we can call when we cd into a directory:
|if [ "$PWD" != "$PREV_PWD" ]; then|
|if [ -e ".nvmrc" ]; then|
|export PROMPT_COMMAND="$PROMPT_COMMAND enter_directory;"|
All this is doing is
- checking to see if the current directory matches the previous directory
- if it doesn’t , then it stores the current directory to the previous’ variable
- then it checks to see if a .nvmrc file exists
- if so, then tell nvm to use it
- lastly we tell the OS to call this command any time we do something in Terminal/Bash