n00bs
require
to include modules.exports
to make things available.An ecosystem for JavaScript outside the browser
"What I’m describing here is not a technical problem. It’s a matter of people getting together and making a decision to step forward and start building up something bigger and cooler together."
// hello.js
console.log('Hello World');
// app.js
require('./hello.js');
// foo.js
foo = function () {
console.log('foo!');
}
// app.js
require('./foo.js');
foo();
// bar.js
module.exports = function () {
console.log('bar!');
}
// app.js
var bar = require('./bar.js');
bar();
// fiz.js
exports.fiz = function () {
console.log('fiz!');
}
// app.js
var fiz = require('./fiz.js').fiz;
fiz();
// buz.js
var Buz = function () {};
Buz.prototype.log = function () {
console.log('buz!');
};
module.exports = new Buz();
// app.js
var buz = require('./buz.js');
buz.log();
// baz.js
var Baz = function () {};
Baz.prototype.log = function () {
console.log('baz!');
};
exports.Baz = new Baz();
// app.js
var baz = require('./baz.js').Baz;
baz.log();
// doo.js
var Doo = function () {};
Doo.prototype.log = function () {
console.log('doo!');
}
module.exports = Doo;
// app.js
var Doo = require('./doo.js');
var doo = new Doo();
doo.log();
// qux.js
var Qux = function () {};
Qux.prototype.log = function () {
console.log('baz!');
};
exports.Qux = Qux;
// app.js
var Qux = require('./qux.js').Qux;
var qux = new Qux();
qux.log();
Named exports - one module, many exported things
Anonymous exports - simpler client interface
module.exports
exports
exports
VS. module.exports
exports
is an alias to
module.exports
.
> module.exports.fiz = "fiz";
> exports.buz = "buz";
> module.exports === exports;
true
exports
directly
(instead of exports.something
)
will overwrite the exports alias.
> module.exports.qux = "qux";
> exports
{ qux: "qux" }
> exports === module.exports
true
> exports = "wobble wibble wubble!";
> exports === module.exports
false
> exports
"wobble wibble wubble!"
> module.exports
{ qux: "qux" }
// module.exports is canonical