nodeJS require.paths 解决问题
我试图相对而神秘地要求一个文件,以下情况正在发生
这效果很好,指向 /Users/marcos/Desktop/Taper/lib/utils.js
myPath = "/Users/marcos/Desktop/Taper/lib/./utils";
require(myPath);
这不是,但它应该指向完全相同的文件:
require.paths.unshift("/Users/marcos/Desktop/Taper/lib")
require("./utils"); //Doesn't work with './'
require("utils"); //Works Fine
任何人都知道为什么在这种情况下我仍然不能使用 ./
来加载路径,因为
require("path").resolve("/Users/marcos/Desktop/Taper/lib", "./utils")
结果是:
"/Users/marcos/Desktop/Taper/lib/utils"
无论如何?
提前致谢
I am trying to require a file relatively and mysteriously the following is happening
This works well which points to /Users/marcos/Desktop/Taper/lib/utils.js
myPath = "/Users/marcos/Desktop/Taper/lib/./utils";
require(myPath);
This doesn't but it should point to exactly the same file:
require.paths.unshift("/Users/marcos/Desktop/Taper/lib")
require("./utils"); //Doesn't work with './'
require("utils"); //Works Fine
Anyone knows why I can't still use ./
in this case for loading the path since
require("path").resolve("/Users/marcos/Desktop/Taper/lib", "./utils")
results in:
"/Users/marcos/Desktop/Taper/lib/utils"
anyway?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更新:
来自文档:
这是原始答案,引用
require.paths
(不再支持):来自 文档:
在节点中,
require.paths
是一个字符串数组,表示模块搜索时的路径不以'/'
、'./'
或'../'
. 为前缀(强调我的)
UPDATED:
From the documentation:
Here’s the original answer, which refers to
require.paths
(which is no longer supported):From the documentation:
In node,
require.paths
is an array of strings that represent paths to be searched for modules when they are not prefixed with'/'
,'./'
, or'../'
.(emphasis mine)
您可以使用
NODE_PATH
传递该示例:
You can pass that using
NODE_PATH
Example:
我创建了一个名为rekuire的新节点模块。
它允许您在不使用相对路径的情况下“要求”。
在测试/重构方面,这可以节省大量时间。
I created a new node module called rekuire.
It allows you to "require" without using relative paths.
It's a big time saver when it comes to testing/refactoring.