简体   繁体   English

文件夹作为模块内的文件夹作为模块NodeJS

[英]Folders as modules within folders as modules NodeJS

I am having trouble requiring from parent directories within NodeJS. 我在NodeJS的父目录中要求时遇到麻烦。 I have read this post, but still couldn't figure it out. 我已经阅读了这篇文章,但仍然无法弄清楚。

node.js require from parent folder node.js从父文件夹要求

This is my file structure: 这是我的文件结构:

-- components/
    -- windows/
        -- index.js
    -- index.js
-- main.js

This is the code: 这是代码:

// /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)
}

When I run main.js , the inner() function prints undefined . 当我运行main.jsinner()函数显示undefined

Why is it printing undefined? 为什么打印未定义? Shouldn't it print foo? 它不应该打印foo吗? Am I missing something about how Node works? 我是否缺少有关Node工作原理的信息?

You just built up a "circular dependency". 您刚刚建立了一个“循环依赖”。 /components/windows/ requires /components/ , which requires /components/windows/ , which requires ... /components/windows/要求/components/ ,这需要/components/windows/ ,要求...

To resolve those nevertheless, NodeJS initializes the exports to an empty object and rewrites them to the exports object after the module initialized. 尽管如此,为了解决这些问题,NodeJS将导出初始化为一个空对象,并在模块初始化后将它们重写为exports对象。 Therefore you can access /components/windows from inside /components/ but not the other way round. 因此,您可以从/components/内部访问/components/windows ,但不能反过来。

To remove the circular dependency, move foo to another file that you require in both modules. 要删除循环依赖关系,请将foo移动到两个模块中都需要的另一个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM