loading...

Running Local NPM Executables

hkly profile image hkly Updated on ・1 min read

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)/$*
}

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!

Posted on by:

hkly profile

hkly

@hkly

Bay Area born and raised QTPOC developer, doodler, dreamer.

Discussion

markdown guide
 

Another option is using npx (which now comes with npm; example: npx jest src/*.test.js). It'll use npm bin executables, fall back to global, and if those aren't there, download to a tmp dir and run the command.

 

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

 

If you install a package globally, using npm install -g you should be able to call the your package from your command line without any tricks.

Make sure you have added ~/npm-global/bin and ~/npm/bin to your PATH.

 

I had this:

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

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

 

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