简体   繁体   中英

Should node.js modules export named functions or an object?

Which is the better pattern to use when creating modules in Node.js that have multiple functions that are called "statically" ie not using the new keyword. Is there an equivalent in ES6 I am missing?

Pattern 1.

// math.js
module.exports.add = (x, y) => {
    return x + y;
}

module.exports.multiply = (x, y) => {
    return x * y;
};

// app.js
const math = require('./math.js');
console.log(math.add(2, 3));

Pattern 2.

// math.js
module.exports = {
    add: (x, y) => {
        return x + y;
    },
    multiply: (x, y) => {
        return x * y;
    }
};

// app.js
const math = require('./math.js');
console.log(math.add(2, 3));

By default module.exports is an empty object. So, there is really no difference in result between your two patterns.

Your first pattern is just adding methods one at a time to the default empty object.

Your second pattern is creating a new object, adding methods to it and then replacing the default module.exports object with your new object.

Which is the better pattern to use when creating modules in Node.js that have multiple functions that are called "statically" ie not using the new keyword.

The result is the same either way and it is merely a matter of a coding style preference for which way you like to write the code.

Is there an equivalent in ES6 I am missing?

ES6 doesn't really introduce anything new for this. You're just defining properties of an object.

I guess there is no "correct way" or "correct pattern" for that. In both cases you are telling mostly the same thing. You're just writing it a little bit different. Both will be transformed in an object and imported by some other module.

That being said, I like the second one. It gives me a sense of better "bundling".

I would, though, import as

import { add, multiply } from './math'

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM