How to configure my shell so that nvm use
run automatically every time there's a .nvmrc file on the directory and use the latest version or a global config when there's no .nvmrc file?
If you use zsh (z shell):
Calling 'nvm use' automatically in a directory with a .nvmrc file
Put this into your $HOME/.zshrc to call nvm use automatically whenever you enter a directory that contains an .nvmrc file with a string telling nvm which node to use:
# place this after nvm initialization!
autoload -U add-zsh-hook
load-nvmrc() {
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 load-nvmrc
load-nvmrc
More info: https://github.com/creationix/nvm#zsh
-
6This worked really well for me, but caused a performance hit to
cd
, since it runs every time you change directories. I added[[ -a .nvmrc ]] || return
to the first line of load-nvmrc(), and that significantly improved the performance of it – Belgabad Dec 5 '19 at 21:49 -
1@Belgabad It's more performant, because with your line the script won't check for
.nvmrc
in parent directories and it also won't go back to the defaultnode
version when youcd
out of the project dir. – Rotareti Dec 11 '19 at 21:38
If you use bash you can add this to your ~/.bashrc
file:
enter_directory() {
if [[ $PWD == $PREV_PWD ]]; then
return
fi
PREV_PWD=$PWD
[[ -f ".nvmrc" ]] && nvm use
}
export PROMPT_COMMAND=enter_directory
Excellent answer from @devius.
I just extended it so it can revert to the default version when leaving a directory with .nvmrc
to another without it.
~/.bashrc
:
#
# Run 'nvm use' automatically every time there's
# a .nvmrc file in the directory. Also, revert to default
# version when entering a directory without .nvmrc
#
enter_directory() {
if [[ $PWD == $PREV_PWD ]]; then
return
fi
PREV_PWD=$PWD
if [[ -f ".nvmrc" ]]; then
nvm use
NVM_DIRTY=true
elif [[ $NVM_DIRTY = true ]]; then
nvm use default
NVM_DIRTY=false
fi
}
export PROMPT_COMMAND=enter_directory
-
Using bash on windows this returns
node v.0.0 (64-bit) is not installed.
even though the .nvmrc file has9.3
. – hofnarwillie Jun 25 '18 at 20:24 -
2
-
I should also say that's using nvm-for-windows which is an entirely different beast. But with the above script + modification it works a treat. +1 – hofnarwillie Jun 25 '18 at 20:31
I just found out about Automatic Version Switching for Node.js https://github.com/wbyoung/avn, you can use that.
You can also follow this thread https://github.com/creationix/nvm/issues/110
-
34This is depressing.. is there no limit to the tool stack depth? node → npm → nvm → avn, and back up. sigh I'll play ball, but my passion is waning with each hack. (and thanks for the link, of course, gabo.) – hraban Dec 8 '17 at 12:35
-
None of the comments at the mentioned thread worked with bash for me. Maybe they're all for MacOS. For something that works in Ubuntu check my answer below. – devius Jan 18 '18 at 13:16
This answer is taken from the official nvm documentation.
Put the following at the end of your $HOME/.bashrc
:
find-up () {
path=$(pwd)
while [[ "$path" != "" && ! -e "$path/$1" ]]; do
path=${path%/*}
done
echo "$path"
}
cdnvm(){
cd "$@";
nvm_path=$(find-up .nvmrc | tr -d '[:space:]')
# If there are no .nvmrc file, use the default nvm version
if [[ ! $nvm_path = *[^[:space:]]* ]]; then
declare default_version;
default_version=$(nvm version default);
# If there is no default version, set it to `node`
# This will use the latest version on your machine
if [[ $default_version == "N/A" ]]; then
nvm alias default node;
default_version=$(nvm version default);
fi
# If the current version is not the default version, set it to use the default version
if [[ $(nvm current) != "$default_version" ]]; then
nvm use default;
fi
elif [[ -s $nvm_path/.nvmrc && -r $nvm_path/.nvmrc ]]; then
declare nvm_version
nvm_version=$(<"$nvm_path"/.nvmrc)
# Add the `v` suffix if it does not exists in the .nvmrc file
if [[ $nvm_version != v* ]]; then
nvm_version="v""$nvm_version"
fi
# If it is not already installed, install it
if [[ $(nvm ls "$nvm_version" | tr -d '[:space:]') == "N/A" ]]; then
nvm install "$nvm_version";
fi
if [[ $(nvm current) != "$nvm_version" ]]; then
nvm use "$nvm_version";
fi
fi
}
alias cd='cdnvm'
This is an improvement over:
- @Gabo Esquivel's answer - because you won't have to switch to another tool (
avn
) - @devius's and @Adriano P's answers - which do not deal with situations where you are within a project
This alias would search 'up' from your current directory in order to detect a .nvmrc
file. If it finds it, it will switch to that version; if not, it will use the default version.
-
-
@BossmanT By 'appears a little slow', do you mean you would guess it's slow from looking at what it does, or you actually found it slow to run? – callum Sep 24 '19 at 8:54
-
@callum only from observing it running in my bash environment, no time trials were ran for it however, its about a fraction of a second slower, not anything significant of course – BossmanT Sep 25 '19 at 15:01
-
I couldn’t detect any lag. Running
cd
isn’t something you’re ever likely to do in large batches, so I don’t think it matters unless the lag is noticeable to a human. – callum Sep 25 '19 at 15:12
I tried many solutions for this and nothing worked the way I wanted, so I wrote my own:
ZSH function to auto-switch to correct Node version
As far as I know, this is the only one that meets all the following criteria:
- guarantees you are always on the right version by searching up the directory tree to find the closest
.nvmrc
(just likenvm use
); - can handle any valid
.nvmrc
format; - clearly warns you if no installed version satisfies the
.nvmrc
, - assumes you want
default
if there is no.nvmrc
anywhere up the tree; - is completely silent and fast if you are already on the correct Node version.
Yet another solution using direnv. Direnv comes with OS X and many distros so no installation is needed.
Add these two lines to your .zshenv or .bash_profile depending on which shell you use:
export NVM_DIR="$HOME/.nvm" # You probably have this line already
export NODE_VERSIONS="${NVM_DIR}/versions/node"
export NODE_VERSION_PREFIX="v"
Add an .envrc file to the project root with the contents
set -e
use node
Finally cd to your directory. (Don't forget to source .zshenv)
direnv will ask you to allow load config.
Type direnv allow
and voila!
Note that direnv doesn't support fancy constructs like lts/*
in .nvrmc. On the positive side, direnv supports a bunch of runtimes like node, php, go, pyhton, ruby etc. allowing us to use a single tool to solve path issues.
Extending on @Adriano P answer, I'd propose this version that is less general (only works if .nvmrc
is set on a git repository root), but works in cases when we navigate to elsewhere in project than its root:
_enter_dir() {
local git_root
git_root=$(git rev-parse --show-toplevel 2>/dev/null)
if [[ "$git_root" == "$PREV_PWD" ]]; then
return
elif [[ -n "$git_root" && -f "$git_root/.nvmrc" ]]; then
nvm use
NVM_DIRTY=1
elif [[ "$NVM_DIRTY" == 1 ]]; then
nvm use default
NVM_DIRTY=0
fi
PREV_PWD="$git_root"
}
export PROMPT_COMMAND=_enter_dir
#export PROMPT_COMMAND="$PROMPT_COMMAND;_enter_dir" # use this if PROMPT_COMMAND already defined
I use this zsh configuration framework called Oh My Zsh. It's a very active repository with regular updates. Try it and I'm sure you will love it. Oh, and it has the automatic .nvmrc feature built-in so it's as simple as installing the package thru npm!
For someone still facing the above issue the README for nvm
has this section which would be helpful
https://github.com/creationix/nvm#deeper-shell-integration
Personally I prefer editing the .bashrc
(https://github.com/creationix/nvm#automatically-call-nvm-use) over other solutions.
bash
shell. – d4nyll Feb 4 '19 at 12:01