AMD modules in RequireJS
define(['a'], function(a) {
return function () {};
})
define(function(require, exports, module) {
var a = require('a');
module.exports = function () {};
})
define(function(require) {
var a = require('a');
return function () {};
})
FE compared to BE
- IO is expensive
- IO is async
- Cross domain and security forces
IO is expensive
- At most, one IO operation per module
- Convention: baseUrl + module ID + '.js'
- configuration
IO is async
- Dependency scan
- Execute before current module: consistent
- Callback-based require for dynamic deps
require([someVar + '/thing'], function (mod) {});
Cross domain and security forces
- CORS: use script tags
- eval. Some tools strip, now CSP
- function wrapper avoids those issues
Just always do builds?
- Avoids actually solving problem
- Requires higher barrier to entry
- Perf: dynamic loading
Uses node_modules if not found via config
var requirejs = require('requirejs');
requirejs.config({});
requirejs(['app/main'], function (main) {});
Bridging the gap
- require([])
- define()
- loader plugins
Bridging the gap, ES6
- require([]) - System.import()
- define() - loader.define, later module 'id'?
- loader plugins - ModuleLoader API
npm for front end
- baseUrl + module ID + '.js'
- Flatten dependencies
- Local name different from repo name
- allow config writing?
Advanced AMD capabilities
requirejs.config({
map: {
'some/newmodule': {
'foo': 'foo1.2'
},
'some/oldmodule': {
'foo': 'foo1.0'
}
}
});
Loader instances
// ES6
var loader = new ModuleLoader({});
// RequireJS
var contextRequire = requirejs.config({
context: 'uniquName'
});
Loader plugins
var text = require('text!example.html'),
AccountView = require('element!account-view'),
coffeecriptDep = require('cs!some/thing');
- Declarative dependencies
- Extensible loading
- Participate in builds, inlining