On Github dilvie / slides-modular-javascript
"Absorb what is useful, discard what is not, add what is uniquely your own." ~ Bruce Lee
Eric Elliott
'use strict'; // You should always do this. var foo = function () { return true; }; module.exports = foo;
var foo = require('./foo.js'); foo(); // true
Modules should be:
DOT (Do One Thing)
Open to extension, closed to modification
"Program to an interface, not an implementation."
~ GoF, "Design Patterns"
// Not exported. var fullName = function fullName(firstName, lastName) { return firstName + ' ' + lastName; } module.exports = function person(options) { return { firstName: options.firstName, lastName: options.lastName, // Hides internal implementation. name: function name() { return fullName(this.firstName, this.lastName); } }; };
It’s not the daily increase but daily decrease.
Hack away at the unessential. ~ Bruce Lee
module.exports.foo = function () { return 'foo'; }; module.exports.bar = function () { return 'bar' }; module.exports.baz = function () { return 'baz'; };
var foo = require('lame').foo, bar = require('lame').bar, baz = require('lame').baz;
var foo = require('foo'), bar = require('bar'), baz = require('baz');
var http = require('http'), server = http.createServer(); server.listen(3000, function () { setTimeout(function () { server.close(); }, 30000) });
var Widget = require('widget'), myWidget = new Widget('clock');
var widget = require('widget'), myWidget = widget();
module.exports = function widget(options) { return { name: options.name, el: document.createElement(options.tagName || 'div'), template: '<div class="content"></div>' } };
Stampit: Compose factory functions.
module.exports = function (options) { return stampit.compose(widget, eventEmitter, list, touch, intfiniteScroll); };
Node Packaged Modules (60k+175/day)
major.minor.patch
"dependencies": { "public": "git://github.com/user/repo.git#ref", "private": "git+ssh://git@github.com:user/repo.git#ref" }
$ npm init
$ npm version <major|minor|patch>
# Publish publicly! # Get famous! # Make friends! $ npm publish
npm run <script-name>
$ npm run jshint
require(‘modules’) in the browser.
$ npm install -g browserify
(~60k modules)
$ browserify index.js -o bundle.js
$ browserify index.js -o bundle.js --debug
$ browserify index.js | uglifyjs -c > bundle.min.js
$ browserify -t uglifyify index.js -o bundle.min.js
https://github.com/substack/node-browserify/wiki/list-of-transforms
$ browserify -s <namespace> index.js -o bundle.js
Module will be at window.namespace