Last Updated: February 25, 2016
·
12.49K
· namuol

Automatically update $PATH with proper node_modules/.bin

I often dislike installing NPM executables globally (i.e. with npm install -g) since it can lead to mismatched dependencies (i.e. I may require express 3.x in one project, but 2.x in another) and general confusion.

NPM is smart enough to ensure the correct package is installed, but it installs it locally (as it should) and simply adding ./node_modules/.bin to my $PATH doesn't always cut it, since more often than not I find myself in a subdirectory of my project.

The npm bin command will output the absolute path to the node_modules/.bin by searching PWD and parent directories for package.json and node_modules:

~/projects/foo $ npm bin
/home/namuol/projects/foo/node_modules/.bin

This is useful, but it's tedious to type something like $(npm bin)/express to run the correct executable.

But with the power of PROMPT_COMMAND, there's an elegant solution!

If you want your $PATH to automatically update based on your current working directory, add this to the end of your .bashrc-equivalent (and after anything that defines $PATH):

__OLD_PATH=$PATH
function updatePATHForNPM() {
  export PATH=$(npm bin):$__OLD_PATH
}

function node-mode() {
  PROMPT_COMMAND=updatePATHForNPM
}

function node-mode-off() {
  unset PROMPT_COMMAND
  PATH=$__OLD_PATH
}

# node-mode  # Uncomment to enable node-mode by default

This may add a short delay every time the bash prompt gets rendered (depending on the size of your project, most likely), so it's disabled by default.

You can enable and disable it within your terminal by running node-mode and node-mode-off, respectively.

1 Response
Add your response

Good tip, thanks. I've just added to my .bash_profile:

PATH=$PATH:node_modules/.bin

over 1 year ago ·