Smokes your problems, coughs fresh air.

Author: jeroen

Jeroen is a full-stack front-end artisan, photographer and salt water aquarium enthusiast.

Jeroen is one of the co-founders of the FlashMQ MQTT managed hosting service.

Automatically switch node versions between projects

At my day job we work with Node 12 for our projects, but I wanted to check out NuxtJS 3, which requires version 14 or 16. Once I updated npm, I found out me old projects no longer worked properly. Reinstalling node_modules didn’t solve the problem, and besided, I didn’t want to saddle up my colleagues with version incompatibilities I couldn’t detect myself. So, I looked into finding a solution. And found one!

With n you can switch easily between Node versions. To install:

npm install -g n
echo "export N_PREFIX=/home/jeroen/.local/n" >> ~/.bashrc
echo "export PATH=$N_PREFIX/bin:$PATH" >> ~/.bashrc

Don’t install it as root, that will make it much more annoying to work with. 

Now it is easy to change between versions:

n 16
node -v
>> v16.13.1

n 14
node -v
>> v14.18.2

But still, you would have to remember which version is used in which project. That’s not fun at all, so that’s what avn was made for. I guess I’m not the only one who is annoyed by such things.

To install avn:

npm install -g avn avn-nvm avn-n
avn setup

That last command adds a line to ~/.bash_profile, which is ignored in my setup, so I had to move that line to ~/.bashrc :

echo '[[ -s "$HOME/.avn/bin/" ]] && source "$HOME/.avn/bin/" # load avn' >> ~/.bashrc

Now add a .node-version file to the root of your project (or in my case the root of all the projects of my boss):

echo "12.22.8" >> ~/projects/.node-version

I also did the same for my own project (with version 16), and now when I switch to any child folder of ~/projects I see this:

Switching node versions works!

Mission accomplished!


While installing this to Macos, I ran into a bit of trouble:

cb.apply is not a function 🧐

If found this solution for it:

n 10.13.0 # Install node version 10.13.0 by n
rm -R ~/.avn
nvm exec 10.13.0 npm install -g avn avn-nvm avn-n  # Use installed version to install the packages
nvm exec 10.13.0 avn setup

This only works with already installed node versions. When I went to a directory with a node version that isn’t installed yet, I got this:

My current solution is to just install that version manually with n:

n 16.11.1

Mission accomplished again!

© 2024 BigSmoke

Theme by Anders NorenUp ↑