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 whe
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!
https://github.com/robbyrussell/oh-my-zsh
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
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.
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:
.nvmrc
(just like nvm use
);.nvmrc
format;.nvmrc
,default
if there is no .nvmrc
anywhere up the tree;