Reputation: 154
So I am building a database layer and am exposing your standard CRUD (Create, Read, Update, Delete) operations as functions. I'm toiling over which way to export each function.
function func1 () {}
function func2 () {}
module.exports = {
"func1": func1,
"func2": func2
}
var exporting;
exporting.func1 = function() {};
exporting.func2 = function() {};
module.exports = exporting;
or, to just do it directly:
module.exports.func1 = function() {};
module.exports.func2 = function() {};
export func1 = function() {}
export func2 = function() {}
I'm sure it wont break things on any method, but what are the pros and cons (if any) of each?
Upvotes: 4
Views: 69
Reputation:
According with your examples, the example #1 and #2 are the same thing since exports
is an object. You only are changing the way of add entries to this object.
This:
const object = {};
object.func1 = function () { return 'hello'; };
object.func2 = function () { return 'bye'; };
You can write like this:
const object = {
func1: function () { return 'hello'; },
func2: function () { return 'bye'; }
};
The last example owns to ES2015 modules and is not implemented yet in V8 (in which Node.js runs). For this example you need the packages babel and babel-preset-es2015.
However, there is a important difference between using CommonJS and ES2015 modules:
CommonJS modules export values, while ES6 modules export immutable bindings. That means: CommonJS export a copy of the module while ES2015 modules export a reference of it.
See: What do ES6 modules export? | 2ality.com
Upvotes: 3