Module are an important tool for keeping your code clean. I'm going to explain a few patterns for using modeule.exports.
Properties or Methods
For exporting properties or methods, you can simply set exports.something to a function or property. This is the simplest form of exporting a module.
For example, say we have a module we call, letters.js
exports.a = function() {
console.log('A');
}
exports.b = function() {
console.log('B');
}
exports.c = 'C';
When we use the module, we directly access the properties and methods that the module exports.
var letters = require('letters');
letters.a();
letters.b();
console.log(letters.c);
The output from this example would be:
a
b
c
Exporting an Instance
You can also export an instance of an object or create a new object that encapsulates your functions. Either way, you cannot simply set exports = {}
you will need to use module.exports = {}
.
var a = function() {
console.log('a');
}
var b = function() {
console.log('b');
}
var c = 'c';
module.exports = {
a: a,
b: b,
c: c
}
Again, when using the module we can directly access the object instance's method.
var letters = require('./letters');
letters.a();
letters.b();
console.log(letters.c);
Exporting a Class
The first two examples allow us to access functions and properties, but what if we want to export a class? We need to follow a similar pattern to the previous example and use module.exports
.
var letters = function() {
this.a = function() {
console.log('a');
}
this.b = function() {
console.log('b');
}
this.c = 'c';
}
module.exports = letters;
To use this module, we will retrieve the module and create a new instance before calling the methods.
var Letters = require('./letters');
var letters = new Letters();
letters.a();
letters.b();
console.log(letters.c);