Effective nodejs version management for the busy developer
Jérémie Chauvel2 min read
I highly recommend setting up nodejs with a version manager, nvm was and still is a popular option, however, I now recommend and have been using fnm, a simpler and faster alternative to manage my nodejs versions.
Install a nodejs version manager: FNM with automatic version switching
To install fnm, follow the installation steps.
I highly recommend installing the autocompletion, if using zshrc, add this in your ~/.zshrc
:
# if fnm is installed, add to path and load autocomplete
if [ -d ~/.fnm ]; then
path+=~/.fnm
# setup env and allow for automatic node version change when directories contains `.node-version` or `.nvmrc`
eval "$(fnm env --shell=zsh --use-on-cd)"
# shell completion
source <(fnm completions --shell zsh) > /dev/null 2>&1
compdef _fnm fnm
compdump
fi
Restart your shell to take those changes into account: exec $SHELL -l
Use a nodejs version
Then you can easily install and switch node versions:
node -v
# install a version
fnm install lts/iron
# switch to version
fnm use lts/iron
# you can switch to a set version by number as well (eg. v20.9.0)
node -v
Project setup to promote the correct nodejs version
When using node in a project, I recommend:
- Setting up a
.nvmrc
file at the root of your project to declare the used nodejs version:
lts/iron
- Using the same version in your runtime, CI, for example with docker:
FROM node:iron-alpine
- In your project package.json, I recommend using the
engines
field to declare the nodejs version:
{
"engines": {
"node": ">=20",
"pnpm": ">=8"
}
}
as well as using engine-strict in your .npmrc
file:
engine-strict=true
Another option is using a preinstall hook for pnpm.
Bonus using pnpm as a package manager
I also recommend using pnpm as a package manager, it’s faster and more efficient than npm or yarn with great capabilities concerning monorepo setup. On recent nodejs versions (v16.13+), you can install it easily with:
corepack enable && corepack prepare pnpm@latest --activate
use engines to enforce usage of pnpm or a preinstall hook:
{
"engines": {
"pnpm": ">=8"
}
}
or
{
scripts: {
"preinstall": "npx only-allow pnpm",
}
}