Should node.js modules export named functions or objects?

What is the best template to use when creating modules in Node.js that have several functions called “statically”, i.e. Do not use a keyword new. Is there an equivalent in ES6 that 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));
+4
source share
2 answers

The default module.exportsis an empty object. Thus, there is no difference in the results between your two templates.

Your first template simply adds methods one at a time to an empty object by default.

, , module.exports .

Node.js , "", .. .

, , .

ES6 , ?

ES6 . .

+5

, " " " ". . . - .

, . "".

, ,

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

Source: https://habr.com/ru/post/1662715/


All Articles