Search code examples
javascriptrequire

Pass a value to exported function using require


If I export a function like this:

const foo = "text";
const bar = function() {
    ...
}

module.exports = {
    foo,
    bar,
};

Is there any way to run the function bar when importing using require, e.g.

const { bar } = require('./myExports.js')('argForBar');

??

(currently when I do this I get the error TypeError: require(...) is not a function)


Solution

  • require('./myExports') returns an object, so you can't just invoke it like a function. If you export just an object with two fields, you will always get that 'require(...) is not a function' error.

    You have alternatives like:

    const bar = require('./myExports.js').bar('argForBar');
    

    which doesn't need destructuring,or:

    const {barF} = require('./myExports.js');
    const bar = barF('argForBar');
    

    Which destructures the bar function into the barF const, then call it.

    Is there a problem with any of those?

    At worst, you can do this trick, and export a function which happens to have properties, instead of a plain object:

    const foo = "text";
    const bar = function() {
        ...
    }
    
    const exported = function(param){
        return bar(param)
    }
    
    exported.foo = foo;
    exported.bar = bar;
    
    module.exports = exported;
    

    This way, you make the module callable as the bar function, while it still is an object with the foo and bar properties. But this is completely convoluted and I don't feel is what you're looking for.