Reputation: 533
I know I can change the node version by nvm use
CLI command. However, I want to set specific node version differently for a certain project(folder). It's changed via nvm use
command but it's reverted to default version
whenever I restart the terminal
or webstorm
IDE.
How can I set nvm
remember this different version for a certain project(folder)?
Upvotes: 53
Views: 57021
Reputation: 3996
nvm use
Use case:
.nvmrc
file in the desired directory and add your required <node version>
Ex:
18
or18.1
or18.3.1
and ensure the specified version is installed on your machine. If 18 is mentioned, any installed version with a major as 18 will be picked.
.zshrc
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
nvm_auto_use() {
local node_version="$(nvm version)"
local nvmrc_path="$(nvm_find_nvmrc)"
if [ -n "$nvmrc_path" ]; then
local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")
if [ "$nvmrc_node_version" = "N/A" ]; then
nvm install
elif [ "$nvmrc_node_version" != "$node_version" ]; then
nvm use
fi
elif [ "$node_version" != "$(nvm version default)" ]; then
echo "Reverting to nvm default version"
nvm use default
fi
}
add-zsh-hook chpwd nvm_auto_use
nvm_auto_use
PS: All the child directories inside the directory with
.nvmrc
also inherit the node version
Upvotes: 13
Reputation: 2366
You can use a .nvmrc
file in the root of the project with the version you want to use. For example v12.4.0
or v10.16.0
.
You have to make sure that this version is installed or it will use the default node version in your machine.
Upvotes: 67
Reputation: 1
One solution that I've found that works for me is creating an alias in your terminal of choice, in my case in .zshrc
so that I can cd into the folder project and change the node version at the same time so I don't forget every time I get to that specific folder to change the node version with nvm
. The alias looks like that:
alias foo='cd ~/route/to/project/folder && nvm use <node_version>'
Upvotes: 0
Reputation: 493
One more method could be to use direnv. Create one file .envrc
at the root of the folder where you want to use a different node version.
For example:
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
nvm use <node_version>
Then run to allow using of this .envrc
file.
direnv allow
Upvotes: 3
Reputation: 1819
For example, you want your default node
version for this project to be v12
.
Open your command line in the project root folder, then run nvm use 12
, then run node -v > .nvmrc
.
It won't solve your issue completely because you'll anyway have to run nvm use
just without the version.
Upvotes: 10