【问题标题】:Exporting two module under same directory not working when requiring from same file需要从同一文件中导出同一目录下的两个模块不起作用
【发布时间】:2018-10-24 05:32:57
【问题描述】:

我在同一个目录下有两个js文件: main/file1.jsmain/file2.js。然后我在我的测试文件夹下调用它test/files.js

如果我的 file1.js 中有这个:

function file1(){
    let result = "a";
    return result;
}
module.exports = file1

然后是我的 file2.js:

let v = "c" //this is the error that make file2 undefined.  scope issue.
function file2(){
    let result = "b";
    return v;
}
module.exports = file2

然后在我的测试文件中我需要这两个文件。 file1 的 steps 函数工作正常,但 file2 的 steps2 未定义。有什么想法吗?

const assert = require('assert'); 
const steps = require('../main/steps');
const steps2 = require('../main/steps2');

describe('steps', function(){
    it('make steps', function(){
        assert.equal(file1(), 'a');
    });
    it('make steps2', function(){
        assert.equal(file2(), 'b');
    });
})

【问题讨论】:

  • 如果你颠倒订单会发生什么?
  • 您的文件名为file1.jsfile2.js,但您需要steps.jssteps2.js。这只是示例中的拼写错误,还是实际代码?
  • @Cully 不是错字,我需要const steps2 = require('../main/steps2');,因为step2 正在被导出到file2 中。
  • @Bravo,颠倒测试文件中的要求顺序?
  • @MingHuang 你不需要函数名,你需要文件名。应该是const steps = require('../main/file1'); const steps2 = require('../main/file2');

标签: javascript node.js mocha.js


【解决方案1】:

当您需要文件名时,您需要函数名。您的要求应如下所示:

const steps = require('../main/file1');
const steps2 = require('../main/file2');

【讨论】:

  • @Bravo 我猜巧合的是有一个名为../main/steps.js的文件
  • 这很好用。你是对的,导入应该是文件名,事实证明我的 file2 的代码存在一些问题(范围问题)。我将在那里添加该错误以反映错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 2012-12-31
  • 2023-03-28
相关资源
最近更新 更多