javascript 需要在 node.js 中使用 npm 模块的帮助
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6463684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Help requiring a npm module in node.js
提问by Alex Wayne
I feel like I'm missing some very basic here...
我觉得我在这里缺少一些非常基本的东西......
So I install a npm library with npm install somelib
. And from what I have read I should then be able to simply do a
所以我安装了一个 npm 库npm install somelib
。从我读过的内容来看,我应该能够简单地做一个
var somelib = require('somelib');
But it fails to find anything. I do have a node_modules
directory at the root of my app, but it doesn't seem to pick it up.
但它找不到任何东西。我的node_modules
应用程序的根目录下确实有一个目录,但它似乎没有找到它。
I tried require.paths.push('node_modules')
but it doesn't help. The only thing that seems to work is this:
我试过了,require.paths.push('node_modules')
但没有帮助。唯一似乎有效的是:
require.paths.unshift('.');
var somelib = require('node_modules/somelib/lib/somelib');
Which makes me feel like this is far more work than I actually need to do to load a npm library. What am I doing wrong here? I thought that installing modules in the app meant I didnt have to futz with environment variables or paths much?
这让我觉得这比加载 npm 库实际需要做的工作要多得多。我在这里做错了什么?我认为在应用程序中安装模块意味着我不必过多地使用环境变量或路径?
回答by balupton
It's possible that somelib
does not have a main
file defined in their package.json
or that it is incorrectly referenced. If somelib
doesn't have a main
but does have a directories.lib
then you can do require('somelib/thefile.js')
instead.
可能somelib
没有main
在他们的文件中定义文件package.json
或者它被错误地引用。如果somelib
没有main
但确实有,directories.lib
那么你可以做require('somelib/thefile.js')
。
If somelib
is written in coffeescript and your app isn't, you'll need to require('coffee-script')
first.
如果somelib
是用 coffeescript 编写的,而您的应用程序不是,则您需要require('coffee-script')
先。
Update:as js2coffee
is coffeescript, I'm going with you need to do the latter.
更新:就像js2coffee
咖啡脚本一样,我和你一起去,你需要做后者。
回答by Amadan
Having the specific module name instead of "somelib" might help... but check the package's package.json
file. Display the require.paths
and compare. Read up on node's module system
使用特定的模块名称而不是“somelib”可能会有所帮助...但请检查包的package.json
文件。显示require.paths
并比较。阅读节点的模块系统