需要 node.js 中的 npm 模块的帮助 [英] Help requiring a npm module in node.js
问题描述
我觉得这里缺少一些非常基本的东西...
I feel like I'm missing some very basic here...
所以我用 npm install somelib
安装了一个 npm 库.从我读过的内容来看,我应该能够简单地做一个
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
var somelib = require('somelib');
但它找不到任何东西.我的应用程序根目录中有一个 node_modules
目录,但它似乎没有找到.
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.
我尝试了 require.paths.push('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.unshift('.');
var somelib = require('node_modules/somelib/lib/somelib');
这让我觉得这比加载 npm 库实际需要做的工作要多得多.我在这里做错了什么?我认为在应用程序中安装模块意味着我不必过多地使用环境变量或路径?
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?
推荐答案
somelib
可能没有在其 package.json 中定义
或者它被错误地引用.如果 main
文件somelib
没有 main
但有 directories.lib
那么你可以做 require('somelib/thefile.js')
代替.
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
是用 coffeescript 编写的,而你的应用不是,你需要先require('coffee-script')
.
If somelib
is written in coffeescript and your app isn't, you'll need to require('coffee-script')
first.
更新:因为js2coffee
是coffeescript,我和你一起去,你需要做后者.
Update: as js2coffee
is coffeescript, I'm going with you need to do the latter.
这篇关于需要 node.js 中的 npm 模块的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!