【发布时间】:2019-04-14 12:52:29
【问题描述】:
我无法从 NodeJS 中的父目录请求。我已经阅读了这篇文章,但仍然无法弄清楚。
node.js require from parent folder
这是我的文件结构:
-- 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 时,inner() 函数会打印出undefined。
为什么打印未定义?它不应该打印 foo 吗?我是否错过了有关 Node 工作原理的一些信息?
【问题讨论】:
-
你有一个循环依赖,这是行不通的。
require("./..")返回一个空对象,该导出后来被components/index.js中的module.exports =赋值覆盖。改用依赖注入。 -
什么是依赖注入? @Bergi
标签: javascript node.js node-modules circular-dependency