Here's how I do it, usually similar to Ross Shannon's answer, with a few differences:
- You can specify the version of Node only in
package.json , without requiring a .nvmrc file - You can also specify the version of Node directly in
.envrc , again without the .nvmrc file - I am not adding
node_modules/.bin to PATH, but if this is your preferred behavior, just add PATH_add node_modules/.bin to the use_nvm function.
For me, support for choosing Node for package.json is important, not .nvmrc , because I did not want to worry about synchronizing two files (especially in a project with several collaborators). However, this solution still works with .nvmrc .
This solution requires direnv , nvm and optionally (if you want to be able to select the Node version from package.json) jq .
In the ~/.config/direnv/direnvrc file, add the following:
# To use: # 1) Node version specified in package.json, in .envrc add: # use nvm package.json # This requires that package.json contains something like # "engines": { # "node": ">=6.9.2" # }, # # 2) Node version specified in .envrc add: # use nvm 6.9.2 # # 3) Node version specified in .nvmrc, in .envrc add: # use nvm use_nvm() { local node_version=$1 if [[ $node_version = "package.json" ]]; then if has jq; then node_version=$(jq --raw-output .engines.node package.json | tr -d "<=> ") else echo "Parsing package.json for node version to use with direnv requires jq" fi fi nvm_sh=~/.nvm/nvm.sh if [[ -e $nvm_sh ]]; then source $nvm_sh nvm use $node_version fi }
In the project directory, add the .envrc file that calls use nvm , for example:
use nvm package.json
However, for my .envrc : I prefer something like the following:
if declare -Ff use_nvm >/dev/null; then use nvm package.json fi
for shared projects with shared .envrc , so collaborators who donβt have use nvm fail.
Now, when you enter the project directory, your desired version of Node will be automatically used (for the first time you will be asked to list your changes to .envrc using direnv allow ).