DEV Community

hkly
hkly

Posted on • Edited on

Running Local NPM Executables

Typically, npm command line executables are installed globally so you can run it from whatever project on your machine. However, sometimes you'll want to run a locally installed package. Here's how!

When npm packages with executables are installed locally, they are linked to ./node_modules/.bin within your project. To invoke them, you would have to enter the entire path pointing to the package name.

For example, if you've locally installed gulp for a single project, it would look something like this to invoke it from the project directory: ./node_modules/.bin/gulp

To make life easier, you can add this bit of script to your .bashrc:

npm-run() {
  $(npm bin)/$*
}
Enter fullscreen mode Exit fullscreen mode

What's happening here is npm bin returns the path of where your executables are, and then the package name you want to invoke is inserted where the $* are.

So now, to run gulp all you have to do is npm-run gulp.

You can even define the function with a shorter name instead of npm-run, like nr, or whatever your heart desires :)

Easy as pie!

Top comments (3)

Collapse
 
hkly profile image
hkly

Neat, I didn't know they added that! :)

Collapse
 
thibmaek profile image
Thibault Maekelbergh

I had this:

function npm-do {
  (PATH=$(npm bin):$PATH;
   eval $@;)
}

Seems very equal, is this considered safer or maybe yours is?

Collapse
 
hkly profile image
hkly

Hm, I don't actually know enough bash to know which is safer. Does anyone else know?