当一个模块位于另一个模块的父目录中时,当模块之间存在循环依赖时,导入的模块是未定义的

Imported module is undefined when there's a circular dependency between the modules when one module is in the parent directory of the other module

文件结构是

-src
--Visitor
---visitor.model.js
---Sessions
----session.model.js

在 visitor.model.js 文件中

const {Sessions} = require('./Sessions/session.model');
const Visitor = {};

Visitor.visitorFunc = () => {


}

Sessions.sessionFunc();

module.exports = {Visitor: Visitor};

在session.model.js文件中

const {Visitor} = require('../visitor.model.js');

const Session = {};

Sessions.sessionFunc = () => {

}

Visitor.visitorFunc();

module.exports = {Session: Session};

当我在访问者文件中进行这样的导入时,会话未定义。这是什么原因..它是递归调用导入吗?

您的 visitor.model.js 文件在 Sessions 目录之外。为了导入 session.model.js 您需要提供该文件的绝对路径。所以你的要求声明应该是这样的

const { Sessions } = require('../Sessions/session.model.js');

节点中允许循环依赖

https://nodejs.org/api/modules.html#modules_cycles

When main.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.

因为 SessionVisitor 听起来像是具有 M:N 关系的数据库模型,循环依赖是可行的方法(例如:连接查询)

How to deal with cyclic dependencies in Node.js

但如果可以的话,避开它们会不会那么混乱。

正如上面的@prashand 给出了在导出当前模块后必须进行导入和调用导入函数的原因。上面的示例稍作更改如下

const Visitor = {};

Visitor.visitorFunc = () => {

  console.log('hello from visitor model');
}


module.exports = {Visitor: Visitor};
// import session.model after exporting the current module

const {Session} = require('./Sessions/session.model');

// then call the required function
Session.sessionFunc();

只需使用 exports.someMember = someMember 而不是 module.exports = { someMember }