assigning “exports” to a function in nodejs module doesn't work

后端 未结 2 1632
暗喜
暗喜 2021-01-29 05:04

in one file (otherFile.js) I have this:

exports = function() {}

in my main file I have this:

var thing = require(\'./otherFile.         


        
2条回答
  •  攒了一身酷
    2021-01-29 05:52

    If you want to change the exported object itself you will have assign it to module.exports. This should work (in otherFile.js):

    module.exports = function() {}
    

    To elaborate a little more why:

    Reassigning a variable does not change the object it referenced before (which is basically what you are doing). A simple example would be this:

    function test(a) {
        a = { test: 'xyz' };
        console.log(a);
    }
    
    var x = { test: 'abc' };
    test(x);
    
    console.log(x);
    

    Basically by assigning exports to the function you'd expect the variable x to have a value of { test: 'xyz' } but it will still be { test: 'abc' } because the function introduces a new variable (which is still referencing the same object however so changing a.test will change the output of both). That's basically how CommonJS modules (which is what Node uses) work, too.

提交回复
热议问题