Can’t require global npm module

2019-04-12 01:50发布

问题:

I have the following problem. I install uuid with npm install -g uuid. When I try to run the following code:

var uuid = require("uuid");
console.log(uuid.v1());

an exception is thrown:

module.js:339
throw err;
^

Error: Cannot find module 'uuid'
at Function.Module._resolveFilename (module.js:337:15)
at Function.Module._load (module.js:287:25)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.<anonymous> (d:\CodingProjects\HTML\TestJavascript.js:16:12)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)

If I install the module locally with npm install uuid it works fine. But why is that? What should I do, to make my global packages working? I tried to download it from Language & Frameworks -> Javascript -> Libraries, but I still get an exception if I don't install it locally for my project.

Thanks in advance.

回答1:

The reason is in how npm installs packages.

When you run npm install -g <package>, you tell npm to install the <package> globally. This works when you want to use the package as a command line tool, like, for example, Gulp:

$ npm install -g gulp
$ cd path/to/project
$ gulp

However, this does not work when you want to depend on a package.

To depend on a package, you should install it locally, i. e. in the project directory. This is one of the npm’s key benefits: local installation makes managing dependencies and upgrading them much easier for you. The npm install command without -g flag is dedicated exactly for that. When you run

$ npm install uuid

in, say, foo directory, a foo/node_modules directory is created, and uuid module is installed there. After that, you could create a .js file in the foo directory (or any its subdirectory), require the uuid module from it, and everything will work.


As to WebStorm: downloading a library from Language & Frameworks → Javascript → Libraries does not actually download an npm package, it just downloads and installs the library type definitions. Type definitions help WebStorm build better autocompletion when you use a library in your code.



回答2:

If you would like to use your global packages, all you need to do is create a link between your global package from within your local directory. This is also known as creating a symbolic link (symlink).

So, running the "npm link uui" in your local directory would allow you to use the global package wihout having to download it into your local directory. If you analyze the local directory you'll notice that a (linked) folder has been created, meaning it is merely a pointer to the global package.

So, in short, if you want to use global packages, then "npm link" is the way to do it.