Madhusudhan Madhusudhan - 1 year ago 56
Node.js Question

Install dependencies globally and locally using package.json

Using npm we can install the modules globally using

option. How can we do this in the package.json file?

Suppose, these are my dependencies in package.json file

"dependencies": {
"mongoose": "1.4.0",
"" : "0.3.3",
"jquery" : "1.5.1",
"jsdom" : "0.2.0",
"cron" : "0.1.2"

When i run
npm install
, I want only
to be installed globally, the rest others should be installed locally. Is there an option for this?

Answer Source

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

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.