【问题标题】: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 谢谢我去看看

标签: javascript node.js


【解决方案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');
}

【讨论】:

    猜你喜欢
    • 2020-04-08
    • 2020-08-18
    • 2013-07-19
    • 2012-10-29
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多