不能要求全局npm模块 [英] Can’t require global npm module
问题描述
我有以下问题。我用 npm install -g uuid
安装uuid。
当我尝试运行以下代码时:
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());
抛出异常:
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)
如果我在本地安装模块 npm install uuid
它运行正常。
但是为什么呢?我应该怎么做才能使我的全球包工作?
我试图从语言&框架 - > Javascript - >库
,但如果我没有在我的项目本地安装它,我仍然会遇到异常。
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.
提前致谢。
推荐答案
原因在于如何 npm
安装包。
当您运行 npm install -g< package>
时,您告诉 npm
全局安装< package>
。当您想要将程序包用作命令行工具时,例如 Gulp :
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.
要依赖包,你应该在本地安装,i。即在项目目录中。这是 npm
的主要优点之一:本地安装可以更轻松地管理依赖关系和升级它们。没有 -g
标志的 npm install
命令专用于此。当你运行
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,例如, foo
目录,创建 foo / node_modules
目录,并在那里安装 uuid
模块。之后,您可以在 foo
目录(或其任何子目录)中创建 .js
文件,并要求 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.
至于WebStorm:从语言和版本下载库。框架→Javascript→库
实际上并没有下载 npm
包,它只是下载并安装库类型定义。类型定义有助于在代码中使用库时,WebStorm可以构建更好的自动完成功能。
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.
这篇关于不能要求全局npm模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!