Skip to content

Instantly share code, notes, and snippets.

@kimmobrunfeldt
Last active July 1, 2023 18:39
Show Gist options
  • Save kimmobrunfeldt/10848413 to your computer and use it in GitHub Desktop.
Save kimmobrunfeldt/10848413 to your computer and use it in GitHub Desktop.
A few Node module export styles. 1 seems to be the most used and I prefer it
// Style 1
// Export all manually
// Good: Calling functions inside the module is convenient
// Bad: module.exports becomes verbose and it's tedious to add new functions
function a() {
b()
}
function b() {
}
module.exports = {
a: a,
b: b
}
// Style 2
// Write all in module.exports
// Good: All functions in the same "package" (only good I could figure out)
// Bad: Hard to read. Wider indentation. Calling other functions is tedious
module.exports = {
a: function() {
module.exports.b()
},
b: function() {
}
}
// Style 3
// Export 'automatically' while writing functions
// Good: module.exports is clean and no hassle needed when adding functions
// Bad: Calling function inside the module is verbose and inconvenient
var exports = {}
exports.a = function() {
exports.b()
}
exports.b = function() {
}
module.exports = exports
// Style 4
// Good for a utils module
// Good: Calling functions inside module is convenient and module.exports is
// clean
// Bad: Syntax is not so clear, though that is arguable
var exports = {}
var a = exports.a = function() {
b()
}
var b = exports.b = function() {
}
module.exports = exports
@Galaxy83
Copy link

var _this = {}

_this.a = function() {
    _this.b()
}

_this.b = function() {
}

module.exports = _this

@gatsbyz
Copy link

gatsbyz commented Jun 6, 2018

Nice!

@p-g-krish
Copy link

Great Work

@mahemoff
Copy link

Style 1 can now be more concise with ES6 literal shorthand:

module.exports = { a, b }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment