cusejuice
cusejuice

Reputation: 10691

Automatically switch to correct version of Node based on project

Let's say I have 2 projects:

example1: requires node version 0.12.1
example2: requires node version 0.10

Currently, when I cd into each project, I use nvm use <version> before running the application.

Is there a way with node or nvm, to automatically switch to the needed version of node when I cd into each project?

Upvotes: 55

Views: 46815

Answers (10)

ryanpback
ryanpback

Reputation: 285

This is what I'm currently using to autoload the node version per project. It updates a variable for use when node is invoked. It prevents switching node versions for every dir change.

https://gist.github.com/ryanpback/1d0b2808f896398eab6106f49b3e99ab

Upvotes: 0

kreo
kreo

Reputation: 11

I think the best solution and totally angnostic is to install Directory Enviroment (direnv), an extension for your shell. It augments existing shells with a new feature that can load and unload environment variables depending on the current directory.

If you use bash as shell add the following line at the end of the ~/.bashrc file:

eval "$(direnv hook bash)"

Instead if you use another shell, simply follow the instructions at this linkenter link description here

Then you must add .envrc file inside your project and specifies the version you'd like to use:

use nodejs 16

After thease steps, it will automatically detects and uses the specified version.

Upvotes: 0

Asad Jivani
Asad Jivani

Reputation: 553

If you're using ubuntu try below,

 "scripts": {
  "prestart": ". ~/.nvm/nvm.sh && nvm use",
   ...
}

if you have created .nvmrc file then you don't need to specify version.

Upvotes: 1

iamogbz
iamogbz

Reputation: 99

If you're fine with using another tool you could use nvshim.

pip install nvshim  # this is all you need to do

It does not slow your shell start up, instead moving the lookup of which node version to when you call node, npm or npx by shimming those binaries. More details in the docs.

Source, I wrote the tool.

Upvotes: 0

illnr
illnr

Reputation: 800

There are also extended (user contributed) bash/zsh shell scripts in the NVM GitHub README:

bash script

Automatically call nvm use
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.

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)

        declare locally_resolved_nvm_version
        # `nvm ls` will check all locally-available versions
        # If there are multiple matching versions, take the latest one
        # Remove the `->` and `*` characters and spaces
        # `locally_resolved_nvm_version` will be `N/A` if no local versions are found
        locally_resolved_nvm_version=$(nvm ls --no-colors "$nvm_version" | tail -1 | tr -d '\->*' | tr -d '[:space:]')

        # If it is not already installed, install it
        # `nvm install` will implicitly use the newly-installed version
        if [[ "$locally_resolved_nvm_version" == "N/A" ]]; then
            nvm install "$nvm_version";
        elif [[ $(nvm current) != "$locally_resolved_nvm_version" ]]; then
            nvm use "$nvm_version";
        fi
    fi
}
alias cd='cdnvm'

zsh script

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

Upvotes: 15

mcnelson
mcnelson

Reputation: 469

Looks for a .nvmrc file in your current directory, every time you cd. If one is found, it loads the version via nvm use and throws out any output.

cd() {
  builtin cd "$@"
  if [[ -f .nvmrc ]]; then
    nvm use > /dev/null
  fi
}
cd .

Upvotes: 46

d4nyll
d4nyll

Reputation: 12677

If you're using a Bash shell, you can define a Bash alias to cd, which will do nvm install / nvm use for you when it detects a .nvmrc file.

alias cd='function cdnvm(){ cd $@; if [[ -f .nvmrc ]]; then <.nvmrc nvm install; fi; };cdnvm'

If you want to make the Node version to revert back to the default when you cd out of the directory, use the following alias:

alias cd='function cdnvm(){ cd $@; if [[ -f .nvmrc && -s .nvmrc  && -r .nvmrc ]]; then <.nvmrc nvm install; elif [[ $(nvm current) != $(nvm version default) ]]; then nvm use default; fi; };cdnvm'

Upvotes: 0

siwalikm
siwalikm

Reputation: 1875

NPM now let's you specify the node version for a project like this npm install node@8.

So next time you do a npm ci or npm i, the correct version is automatically set.

Upvotes: 5

vromanch
vromanch

Reputation: 989

You can add nvm command into package.json file

"scripts": {
  "preinstall": "nvm install 0.12.1",
  "prestart": "nvm use 0.12.1",
  "start": "node ./file1.js"
},

Also set desired version into package.json, so Continuous Integration services would know what version you want to use.

{
  "name": "naive",
  "description": "A package using naive versioning",
  "author": "A confused individual <[email protected]>",
  "dependencies": {
    "express": ">= 1.2.0",
    "optimist": ">= 0.1.0"
  },
  "engine": "node 0.4.1"
}

Upvotes: 17

ferhatelmas
ferhatelmas

Reputation: 3978

Install Automatic Node Version Switching (avn) and add .node-version file that specifies the version you'd like to use with project. It automatically detects and uses it via installed version manager such as nvm and n.

Upvotes: 17

Related Questions