Install dependencies globally and locally using package.json
Due to the disadvantages described below, I would recommend following the accepted answer:
Use
npm install --save-dev [package_name]
then execute scripts with:$ npm run lint $ npm run build $ npm test
My original but not recommended answer follows.
Instead of using a global install, you could add the package to your devDependencies
(--save-dev
) and then run the binary from anywhere inside your project:
"$(npm bin)/<executable_name>" <arguments>...
In your case:
"$(npm bin)"/node.io --help
This engineer provided an npm-exec
alias as a shortcut. This engineer uses a shellscript called env.sh
. But I prefer to use $(npm bin)
directly, to avoid any extra file or setup.
Although it makes each call a little larger, it should just work, preventing:
- potential dependency conflicts with global packages (@nalply)
- the need for
sudo
- the need to set up an npm prefix (although I recommend using one anyway)
Disadvantages:
$(npm bin)
won't work on Windows.- Tools deeper in your dev tree will not appear in the
npm bin
folder. (Install npm-run or npm-which to find them.)
It seems a better solution is to place common tasks (such as building and minifying) in the "scripts" section of your package.json
, as Jason demonstrates above.
New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies
section of your package.json. Anytime you use something from scripts
in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.
For example:
npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally
Then in package.json:
// devDependencies has mocha and babel now
"scripts": {
"test": "mocha",
"build": "babel -d lib src",
"prepublish": "babel -d lib src"
}
Then at your command prompt you can run:
npm run build # finds babel
npm test # finds mocha
npm publish # will run babel first
New NEW Note: For awhile now we have had npx
, which allows you to run the devDependencies commands without needing to add them to your scripts
section (if you want).
For example:
npx webpack
But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:
"scripts": {
"preinstall": "npm i -g themodule"
}
So actually my npm install executes npm install again .. which is weird but seems to work.
Note: you might have issues if you are using the most common setup for npm
where global Node package installs required sudo
. One option is to change your npm
configuration so this isn't necessary:
npm config set prefix ~/npm
, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH
to your ~/.bashrc
.
Another, probably better option is to just use nvm
to manage Node and you won't have that problem.