Wanna see something cool? Check out Angular Spotify 🎧

nvm keeps "forgetting" node version in new VSCode terminal sessions

Problem

In my project, we define engines in package.json like this:

"engines": {
  "node": ">=20.10.0",
  "pnpm": "9.9.0"
}

Recently, when I run a pnpm command, I encountered this error:

Your Node version is incompatible with "/Users/trung.vo/project-a".

Expected version: >=20.10.0
Got: v18.19.1

This is happening because the package's manifest has an engines.node field specified.
To fix this issue, install the required Node version.

I checked the Node version on my machine:

node -v
v18.19.1

I then installed the correct version of Node using nvm and set the default version to 20.10.0:

nvm install 20.10.0
nvm alias default 20.10

However, when I opened a new terminal session in VSCode, the Node version reverted to 18.19.1. See the following gif for more details:

nvm keeps "forgetting" node version in new VSCode terminal sessions

Solution

After exploring multiple Stack Overflow questions, I finally found a working solution.

You need to add the following line at the TOP of your .bashrc or .zshrc file, before anything else:

PATH="/usr/local/bin:$(getconf PATH)"

nvm keeps "forgetting" node version in new VSCode terminal sessions

In my case, I am using oh-my-zsh and the VSCode integrated terminal. Adding the line above to my .zshrc file resolved the issue.

The reason, as explained in the answers below:

Apparently, nvm does not get along with integrated terminals or subshells in these editors. When loading them, the environment variable $PATH is modified internally. According to a comment by one of the contributors of this package in the issue reported NVM fails to load within nested shell #1652:

@charsleysa I know why nvm is throwing this error. In your subshell, somehow the /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin part of your PATH has been moved from the end of the PATH to the start. When nvm is then started, it calls nvm_change_path (my contribution changed it to this from nvm_prepend_path), which modifies the nvm-relevant part of the path in place.

After adding the line above to my .zshrc file, I ran nvm alias default 20.10 again. Upon opening a new terminal session in VSCode, the Node version was correctly set to 20.10.0.

nvm keeps "forgetting" node version in new VSCode terminal sessions

Published 10 Sep 2024

    Read more

     — An error occurred while installing pg (1.5.6), and Bundler cannot continue (when running rails new)
     — Copy Code with Syntax Highlighting from VSCode to PowerPoint
     — Notion: Rounding to 2 Decimal Places
     — Adding "loading=lazy" to GIF files on my 7-year-old Gatsby blog (with ChatGPT assistance)
     — Angular v17’s View Transitions: Navigate in Elegance