我必须导出2种类型的常量和几个函数,如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);
现在我也想导出函数像getUser,我如何改变mymodule.js导出函数,以便消费者.js可以调用udb.getUser
类似的东西,但它不工作,请建议。
module.exports = Object.freeze(Object.assign(Object.create(null), type1, type2)), getUser: function() {}
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();
编辑:添加一个完整的示例
编辑2:更简单
可以使用展开运算符
const type1 = require('./constants1.js');
const type2 = require('./constants2.js');
function getId() {}
function getUser() {}
module.exports = Object.freeze({ getId, getUser, ...type1, ...type2 })