Javascript 文件夹作为模块在文件夹作为模块节点中
我无法从NodeJS内的父目录中请求。我读过这篇文章,但还是不明白 这是我的文件结构:Javascript 文件夹作为模块在文件夹作为模块节点中,javascript,node.js,node-modules,circular-dependency,Javascript,Node.js,Node Modules,Circular Dependency,我无法从NodeJS内的父目录中请求。我读过这篇文章,但还是不明白 这是我的文件结构: -- components/ -- windows/ -- index.js -- index.js -- main.js 代码如下: // /main.js var components = require("./components") components.windows.inner() // /components/index.js module.exports
-- components/
-- windows/
-- index.js
-- index.js
-- main.js
代码如下:
// /main.js
var components = require("./components")
components.windows.inner()
// /components/index.js
module.exports = {
windows: require("./windows"),
foo: "foo",
}
// /components/windows/index.js
var components = require("./..")
module.exports.inner = function() {
console.log(components.foo)
}
当我运行main.js
时,internal()
函数将打印undefined
为什么打印未定义?它不应该打印foo吗?我是否遗漏了一些关于节点如何工作的信息?您刚刚建立了一个“循环依赖关系”<代码>/components/windows/需要/components/
,需要/components/windows/
,需要
为了解决这些问题,NodeJS将导出初始化为空对象,并在模块初始化后将其重写为导出
对象。因此,您可以从/components/
内部访问/components/windows
,但不能反过来访问
要删除循环依赖项,请将foo
移动到两个模块中所需的另一个文件。您刚刚建立了一个“循环依赖项”<代码>/components/windows/需要/components/
,需要/components/windows/
,需要
为了解决这些问题,NodeJS将导出初始化为空对象,并在模块初始化后将其重写为导出
对象。因此,您可以从/components/
内部访问/components/windows
,但不能反过来访问
要删除循环依赖项,请将
foo
移动到两个模块中所需的另一个文件。如果存在循环依赖项,则无法工作require(“./”)
返回一个空对象,该导出稍后会被components/index.js中的module.exports=
赋值覆盖。改用依赖注入。什么是依赖注入@因为你有一个循环依赖,这是不起作用的require(“./”)
返回一个空对象,该导出稍后会被components/index.js中的module.exports=
赋值覆盖。改用依赖注入。什么是依赖注入@Bergiso,将foo
移动到windows/
有意义吗?@matt是的,它会。那么,将foo
移动到windows/
有意义吗?@matt是的,它会。