Understanding npm install -g option

2019-04-16 03:28发布

问题:

Just getting started with node. I'm a little confused about the npm install -g option. Could someone tell me if the following is correct:

  • npm install -g installs global packages in a general location
  • npm install installs packages in the specific folder
  • regardless of how installed all dependencies need to be listed in the json file
  • dependencies not installed with the -g option need to be listed as required in the appropriate *.js file

so for example if installed with the -g option:

var app = express();

and if not installed with the -g option:

var express = require(‘express’);
var app = express();

回答1:

Quite confusing...

NPM has great documentation. Did you read it?

  • https://docs.npmjs.com/cli/install
  • https://docs.npmjs.com/files/folders
  • https://docs.npmjs.com/getting-started/installing-npm-packages-locally
  • https://docs.npmjs.com/getting-started/installing-npm-packages-globally

There is no difference in using the modules. It doesn't change anything if you install global or project-local.

First you have to import/require the module. Then you can use it.

Global installation means every project using the same node installation can require it.

Although there is another dependency if the installation is user-global or system-global.

  • User-global: only projects running by this one user can require.
  • System-global: all projects of all users can require.


回答2:

Installing with -g puts the packages in a location accessible in the path so that the package is available from all applications that require it. Normally, you'll only want to use this option when installing utilities that have their own standalone executables (like WebPack, or the Express CLI).

This has absolutely nothing to do with how packages are loaded in your application. You still need to use require().

NPM is effectively independent from Node.js. It's a package manager that has no bearing at all on how require() works.