On Github herschel666 / Modular-JavaScript-Talk
var some_value = 'foo'; function do_some_stuff() { // … } function do_some_other_stuff() { // … }
var APP = {} || APP; var APP = (function (APP) { APP.someMethod = function () {…} return APP; })(APP); var APP = (function (APP) { APP.someOtherMethod = function () {…} return APP; })(APP); ...
Writing everything in a single file is a no-go!
Including each file with a <script>-tag while keeping the correct order is tedious work to do.
A bunch of <script>-tags, serially processed, is insufficient.
var moduleA = require('modules/module-a'); module.exports.foo = function (bar) { return moduleA.doStuff(bar); };
The Asynchronous Module Definition brings the module system to the browser environment.
define(['modules/deps-a', 'modules/deps-b'], function (depsA, depsB) { var foo = depsA.someMethod(); return { doBar: function (foo) { return depsB.create(foo); } }; });
require(['main'], function (foo) { foo.doBar('foobar'); });
Made by James Burke (@jrburke)
A popular and mature implementation of the AMD-specification
The AMD-syntax
define(['some-module'], function (someModule) { return { foo: function (bar) { return someModule.doStuff(bar); } }; });
The CommonJS-like syntax *
define(function (require, exports, module) { var someModule = require('some-module'); exports.foo = function (bar) { return someModule.doStuff(bar); }; });
*: Does only work in browsers that support Function.prototype.toString
var util = require('util'), str = 'This script\'s path is %s'; module.exports = function () { return util.format(str, __filename); };
(function (root, factory) { if (typeof define === 'function' && define.amd) { define(['exports', 'b'], factory); // AMD } else if (typeof exports === 'object') { factory(exports, require('b')); // CommonJS } else { factory((root.commonJsStrict = {}), root.b); // Browser globals } }(this, function (exports, b) { exports.action = function () { // do stuff … }; }));
Modules finally arrive in JavaScript.
import 'modules/some-module' as someModule; export function foo(bar) { return someModule.doStuff(bar); };
Just one way of importing and exporting.
A decent Loader is there as well.
System.import( ['modules/some-module'], function (someModule) { // do fancy stuff with `someModule` }, function (err) { // something went wrong } );
AMD-style syntax module-loading.
System.load( ['vendor/jake-weary.js'], function (dollarz) { // do crazy stuff }, function (err) { // no jake … } );
Same syntax but different method for loading common JS-files.
Go ye and write modular JavaScript.