【问题标题】:Folders as modules within folders as modules NodeJS文件夹作为模块在文件夹中作为模块 NodeJS
【发布时间】: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


【解决方案1】:

你刚刚建立了一个“循环依赖”。 /components/windows/ 需要/components/,需要/components/windows/,需要...

为了解决这些问题,NodeJS 将导出初始化为一个空对象,并在模块初始化后将它们重写为 exports 对象。因此,您可以从/components/ 内部访问/components/windows,但反之则不行。

要删除循环依赖,请将foo 移动到两个模块中都需要的另一个文件。

【讨论】:

  • 那么,将foo 移动到windows/ 是否有意义?
  • @matt 是的。
猜你喜欢
  • 1970-01-01
  • 2016-02-26
  • 2021-07-01
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
相关资源
最近更新 更多