Matthew Harwood Matthew Harwood - 4 months ago 31
Node.js Question

A dotfile that will set the default node version on a project using nvm?

In ruby when using rbenv you can make a

.ruby-version
file and put it in the local directory. https://gist.github.com/fnichol/1912050
I'm looking for something similar to this using NVM?

Question:

Is there a property to set in package.json or a file to create that will set the default version of node of a project?

Answer

You can do this with a combination of NVM, dotfiles in your project directory, and a little tool called direnv which allows you to load in environment variables on a per-directory basis.

http://direnv.net/

Install NVM and direnv, and then cd to the directory you want to change Node versions in.

Add a file called .nvmrc in that directory, containing just the version number of the Node version you want to auto-switch to, e.g.,:

6.2.2

Then add an environment configuration file called .envrc to your directory, containing this script:

nvmrc=~/.nvm/nvm.sh
if [ -e $nvmrc ]; then
  source $nvmrc
  nvm use
fi

PATH_add node_modules/.bin

If you now cd out of this directory, and then cd back in, direnv will kick in and you should be asked to add the directory to your direnv whitelist by typing direnv allow . at the prompt. Once whitelisted, direnv will auto-run that script whenever you enter this directory, setting your Node version to the version number in .nvmrc.

As a bonus, it will also add the node_modules directory to your PATH, so you can execute binaries from those directories without prepending the node_modules path.

Comments