在另一个文件中导出,在同一个文件中调用[重复]

Posted

技术标签:

【中文标题】在另一个文件中导出,在同一个文件中调用[重复]【英文标题】:Exports within another file, called in the same file [duplicate] 【发布时间】:2019-07-16 14:59:52 【问题描述】:

假设我有两个文件,index.jstest.js

现在它们包含以下代码;index.js

var test = require('./test');

test.execute();

function execute()
  console.log('Execute this from the test file');


module.exports = 
  execute

test.js

var index = require('./index'); 

index.execute();

function execute()
  console.log('Execute this from the index file');


module.exports = 
  execute

它们几乎是一回事,它们所做的只是执行对手的execute()函数。但是,当我启动节点时,我会运行 node index 来启动服务器。现在发生的情况是 test.js 文件的 execute() 函数不存在,因为在导出带有 index.js 的执行函数之前需要测试模块。

解决此问题的好方法是什么?

【问题讨论】:

@JoséAntonioPostigo 谢谢我去看看 【参考方案1】:

在这种情况下,您似乎可以将导出分配到顶部:

index.js

module.exports = 
  execute


var test = require('./test');

test.execute();

function execute()
  console.log('Execute this from the test file');

test.js

module.exports = 
  execute


var index = require('./index'); 

index.execute();

function execute()
  console.log('Execute this from the index file');

【讨论】:

以上是关于在另一个文件中导出,在同一个文件中调用[重复]的主要内容,如果未能解决你的问题,请参考以下文章