NPM

Default package manger for Node.js

About NPM

npm is a package manager for the JavaScript programming language maintained by npm, Inc.

-- Wikipedia

 

Avoid Global Installation of Packages

Quick Instructions

Inside a npm managed directory add the local installation directory to the path:

PATH=`pwd`/node_modules/.bin:$PATH

Strip the first path from PATH:

PATH=${PATH#*:}

Shell Functions

nact saves PATH, then prepends it with the local installation directory, if inside an npm managed directory. It prevents multiple invocations.

ndeact restores the PATH previously saved by nact.

nact () {
    if [ -n "$NPM_MODULES_PATH" ]; then
        echo already activated: $NPM_MODULES_PATH
        return
    fi
    if [ ! -d ./node_modules/.bin ]; then
        echo not in a npm package directory
        return
    fi
    export NPM_MODULES_PATH
    NPM_MODULES_PATH=`pwd`/node_modules/.bin
    export NPM_ACTIVATE_PATH
    NPM_ACTIVATE_PATH=$PATH
    PATH="$NPM_MODULES_PATH:$PATH"
    export NPM_ACTIVATE_PS1
    NPM_ACTIVATE_PS1=$PS1
    PS1="(npm)$PS1"
}
ndeact () {
  if [ -z "$NPM_MODULES_PATH" ]; then
      echo nothing to deactivate
      return
  fi
  unset NPM_MODULES_PATH
  PATH=$NPM_ACTIVATE_PATH
  unset NPM_ACTIVATE_PATH	
  PS1=$NPM_ACTIVATE_PS1
  unset NPM_ACTIVATE_PS1
}

Rationale

It is common to install commandline utilities like Gulp or Vue CLI with -g (global) commandline switch, so they are available via the standard search PATH.

Global installation has several drawbacks, e.g.:

Alternatives

Other, probably more sofisticated techniques exist to acchive the same or similar functionality, see: https://npm.github.io/installation-setup-docs/installing/using-a-node-version-manager.html

 

 

References