I'm trying to refactor some of my JS code and the way I handle exported functions within a Node JS environment. Originally, I'd have multiple functions exported from a JS file for instance utils.js :
const function1 = () => {
// ...
}
// ...
exports.function1 = function1
exports.function2 = function2
exports.function3 = function3
and then imported into my entry JS file as:
const anything = require('./utils')
// usage
anything.function1()
this would work, but my refactor isn't working... in that it's not a function?
const function1 = () => {
// ...
}
// ...
module.exports = {
function1,
function2,
function3
}
And used as...
const anything = require('./utils')
// usage
anything.function1()
Why isn't this now a function when it clearly hasn't changed?
the issue is this you are exporting an object
but without key-value
pair.
Just do it like this
module.exports = {
function1: () => {
return 'Jim';
},
function2: () => {
return 'Jim';
}
};
In this syntax you don't need to export explicitly anything. Just read more about module
exports here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.