Reputation: 68
I have to export 2 type of constants and few functions like getUser.
mymodule.js
const type1 = require('./constants1.js');
const type2 = require('./constants2.js');
module.exports = Object.freeze(Object.assign(Object.create(null), type1, type2))
constants1.js
module.exports = Object.freeze({
DOUBLE: 1,
FLOAT: 2
})
consumer.js
const udb = require('./mymodule.js');
console.log(udb.DOUBLE);
Now I also want to export function like getUser , how do i change mymodule.js to export the functions too , so that consumer.js can call udb.getUser
something like this but it doesnt work, Please suggest.
module.exports = Object.freeze(Object.assign(Object.create(null), type1, type2)), getUser: function() {}
Upvotes: 1
Views: 1120
Reputation: 14904
You could use spread operator
const type1 = require('./constants1.js');
const type2 = require('./constants2.js');
function getId() {}
function getUser() {}
module.exports = Object.freeze({ getId, getUser, ...type1, ...type2 })
Upvotes: 1
Reputation: 977
constant1.js
module.exports = Object.freeze({
DOUBLE: 1,
FLOAT: 2
});
constant2.js
module.exports = Object.freeze({
TRIPLE: 3,
});
mymodules.js
const getUser = ()=> console.log("Something");
const getId = ()=>console.log("Something2");
const type1 = require("./constants1.cjs");
const type2 = require("./constants2.cjs");
const udb = Object.assign(Object.create(null), type1, type2);
udb.getUser = getUser;
udb.getId = getId;
module.exports = Object.freeze( udb );
consumer.js
const udb = require("./mymodule.cjs");
console.log(udb.DOUBLE);
// udb.getUser();
// udb.getId();
EDIT: Added a complete example
EDIT 2: Simpler
Upvotes: 1