8

I would like to install all the dependencies of my package.json file globally. I tried Running

npm install -g

But this will install the dependencies of the package locally.

Is it possible to install all my package dependencies globally?

Sheikh Hasib
  • 7,423
  • 2
  • 25
  • 37
Leo
  • 621
  • 6
  • 9
  • You can read their docummentation: https://docs.npmjs.com/cli/install – Lucas Dias May 28 '18 at 17:41
  • The documentations says that using "-g or --global" should do it, but this is not install the packages globally – Leo May 28 '18 at 17:49
  • 1
    It will install on the global scope the specified packages, not the all the packages inside `package.json`, because in there there are 2 scopes: `devDependencies` and `dependencies`. – Lucas Dias May 28 '18 at 20:01
  • I understand that if I send the packages through the command parameters, example **npm install global -g protractor** is going to work. But what I want is to define a list of packages on the package.json dependencies to be installed globally. – Leo May 28 '18 at 23:09
  • You can do a trick for this. Create a simple js file, create an array for global packages. If this file is called, it will run the command to install all the listed packages in the array, but user need to do for example, `npm install` then `npm run global`. The `global` script you'll reference to the js file. – Lucas Dias May 29 '18 at 13:15
  • I found a very similar question with really good answers. https://stackoverflow.com/questions/6480549/install-dependencies-globally-and-locally-using-package-json – Leo May 29 '18 at 16:50
  • Easier than I though and fault from your part to not searching before. – Lucas Dias May 29 '18 at 17:03

1 Answers1

3

Save the following content in root of project as package.js

let json = require('./package.json')
const ob = json
var a = 'npm i -g '
// @types/slug ^0.9.1
Object.entries(ob['dependencies']).forEach(e => {
    a = a + ' ' + e[0] + '@' + e[1] + ' '
    // console.log(e[0], )
})
const { exec } = require('child_process')
console.log('dependencies', a)
exec(a, (err, stdout, stderr) => {
    if (err) {
        //some err occurred
        console.error(err)
    } else {
        // the *entire* stdout and stderr (buffered)
        console.log(`stdout: ${stdout}`)
        console.log(`stderr: ${stderr}`)
    }
})


var b = 'npm i -g '
// @types/slug ^0.9.1
Object.entries(ob['devDependencies']).forEach(e => {
    b = b + ' ' + e[0] + '@' + e[1] + ' '
    // console.log(e[0], )
})
console.log('devDependencies', b)
exec(b, (err, stdout, stderr) => {
    if (err) {
        //some err occurred
        console.error(err)
    } else {
        // the *entire* stdout and stderr (buffered)
        console.log(`stdout: ${stdout}`)
        console.log(`stderr: ${stderr}`)
    }
})

now run node package.js run it as sudo node package.js if face admin issue

Chetan Jain
  • 236
  • 6
  • 16