Search code examples
javascriptecmascript-5amdcommonjsmodule.exports

how to export a default function and default object


I would like to export as a default object and a default function such that I can use as:

const config = require('./config')

const url = config.url

AND

const config = require('./config')

const url = config({url: 'uniqueurl'}).url

I imagine I need to use module.exports = { default: config } but how do I also add a default function?


Solution

  • module.exports is the single value that you export.

    If you want to export a function, then export a function.

    If you want that function to have properties, then add them as you would to any other object. Functions are objects.

    function myFunction (url) {
        return { url: url };
    }
    
    myFunction.url = "something";
    
    module.exports = myFunction;