How do I use a local version of a module in node.js
. For example, in my app, I installed coffee-script:
npm install coffee-script
You can also use direnv and change the $PATH variable only in your working folder.
$ cat .envrc
> export PATH=$(npm bin):$PATH
Use npm-run.
From the readme:
Any executable available to an npm lifecycle script is available to npm-run
.
$ npm install mocha # mocha installed in ./node_modules
$ npm-run mocha test/* # uses locally installed mocha executable
$ npm install -g npm-run
In case you are using fish shell
and do not want to add to $path
for security reason. We can add the below function to run local node executables.
### run executables in node_module/.bin directory
function n
set -l npmbin (npm bin)
set -l argvCount (count $argv)
switch $argvCount
case 0
echo please specify the local node executable as 1st argument
case 1
# for one argument, we can eval directly
eval $npmbin/$argv
case '*'
set --local executable $argv[1]
# for 2 or more arguments we cannot append directly after the $npmbin/ since the fish will apply each array element after the the start string: $npmbin/arg1 $npmbin/arg2...
# This is just how fish interoperate array.
set --erase argv[1]
eval $npmbin/$executable $argv
end
end
Now you can run thing like:
n coffee
or more arguments like:
n browser-sync --version
Note, if you are bash
user, then @Bob9630 answers is the way to go by leveraging bash's $@
, which is not available in fishshell
.
You don't have to manipulate $PATH
anymore!
From npm@5.2.0, npm ships with npx
package which lets you run commands from a local node_modules/.bin
or from a central cache.
Simply run:
$ npx [options] <command>[@version] [command-arg]...
By default, npx
will check whether <command>
exists in $PATH
, or in the local project binaries, and execute that.
Calling npx <command>
when <command>
isn't already in your $PATH
will automatically install a package with that name from the NPM registry for you, and invoke it. When it's done, the installed package won’t be anywhere in your globals, so you won’t have to worry about pollution in the long-term. You can prevent this behaviour by providing --no-install
option.
For npm < 5.2.0
, you can install npx
package manually by running the following command:
$ npm install -g npx