All my experience with exporting/importing modules has come in ES6 using export
and import
, where you can do something like this to have a single module export a default function as well as separate named functions.
// module.js
export default mainFunction
export { namedFunction }
// main.js
import mainFunction from 'functions'
mainFunction()
import { namedFunction } from 'function'
namedFunction()
However I can't figure out how to do this with ES5 style imports using module.exports
and require
. As far as I understand, I can export either a single default:
// module.js
module.exports = function mainFunction() {}
// main.js
const mainFunction = require('module.js')
Or I can create named exports:
// module.js
module.exports = {
namedFunction: function() {}
}
// main.js
const namedFunction = require('module.js').namedFunction
But I can't do both. I thought I could maybe name one of the exports "default" like this, but it doesn't work
// module.js
module.exports = {
default: function() {},
namedFunction: function() {}
}
// main.js
const mainFunction = require('module.js') // does not work
const mainFunction = require('module.js').default // works, but not what I want
const namedFunction = require('module.js').namedFunction
How can I accomplish this dual default/named export with ES5?