Working on different projects, that use multiple versions of NodeJS? and having trouble setting up the project? then you need to use NVM — Node Version Manager.
Start by running following command.
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
Need a different method to install NVM? check out github readme.
This command installs nvm
on your computer and attempts to add the source lines from the snippet below to the correct profile file (~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc).
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
Once the snippet is added to you profile file, close the terminal and open again. I personally like to do source ˜/.[profile]
in the same terminal.
replace
[profile]
with your profile name
Let's run nvm
this output a huge log of all the options that come with NVM. Let install NodeJS
nvm install 12
the number is the NodeJS Version you would like to install. In the same way, you can install as many versions you like to have.
By installing NodeJS this way you can keep your NPM and Global installs unique to that version. When you switch to a different version, it will have its own configuration without juggling things to get the project up and running for the development.
Switch between multiple versions of NodeJS
At any point, you want to switch between different installed NodeJS versions. Simply Run
nvm use [version]
Automatic Version Switching for Node.js
Let's make it even better by adding AVN - Automatic Version Switching for Node.js, when working with multiple projects it's very easily forgotten what version of NodeJS to use and we could try to run the project in a different NodeJS. To prevent this we can use AVN.
To install avn
run following commands
npm install -g avn avn-nvm avn-n
avn setup
Now, you avn
is ready. All you need to do go into your project directory and create a .node-version
file with the NodeJS version. you can get your NodeJS version by doing node -v
echo "12" > .node-version
Now whenever you switch to your project directory containing .node-version
, your avn will switch to the NodeJS version specified in the file automatically.
Here a list of commands I found myself using
- List all installed NodeJS versions
nvm list
- Setting a default NodeJS version
nvm alias default [version]
I hope this article has helped you improve your NodeJS development environment. For more amazing articles and Jamstack updates, follow us on twitter @stackrole
Top comments (0)