JavaScript Module Strategies
Presented by: Ian McPhail
What is a Module?
// Object Literal
var MyModule = {
property: 'someValue',
method: function () { }
};
// Module Pattern
var Module = (function () {
// Private state
var privateVar,
privateMethod;
privateMethod = function() { };
// Public state
return {
publicVar: 'someValue',
publicMethod: function() { }
};
})();
Why use Modules?
- Code organization
- Encapsulation
- Dependency management
- Optimization
- Reusability
- Collaboration
Global Variables
// app.js
var App = {};
// Code goes here
window.App = App;
// cart.js
function Cart() { }
App.Cart = new Cart();
// overlay.js
function Overlay() { }
App.Overlay = new Overlay();
Pros
- Native browser support
- Easy to implement
- No build step
- Faster initial load time
Cons
Global Variables
- Not scalable
- Fragile code
- Manual dependencies
- Global lookup performance
AMD
// app.js
require(['lib/jquery', './cart', './overlay'], function($, Cart, Overlay) {
// Code goes here
});
// cart.js
define(['lib/jquery'], function($) {
function Cart() { }
return new Cart();
});
// overlay.js
define(['lib/jquery'], function($) {
function Overlay() { }
return new Overlay();
});
- Designed for the browser
- No build step required
- Asynchronous loading
- Flexible format
- Explicit dependencies
- Plugin support
AMD
- Verbose syntax
- Requires script loader
- Extensive configuration
- Asynchronous execution
Pros
Cons
CommonJS
// app.js
var $ = require('jquery');
var Cart = require('./cart');
var Overlay = require('./overlay');
// Code goes here
// cart.js
var $ = require('jquery');
function Cart() { }
module.exports = new Cart();
// overlay.js
var $ = require('jquery');
function Overlay() { }
module.exports = new Overlay();
- Adopted by Node.js
- Access to NPM ecosystem
- Convenient syntax
- Synchronous execution
CommonJS
- Built for the server
- Build tools required
- Large module bundles
- Synchronous loading
Pros
Cons
ES6 Modules
// app.js
import $ from 'lib/jquery';
import Cart from './cart';
import Overlay from './overlay';
// Code goes here
// cart.js
import $ from 'lib/jquery';
function Cart() { }
export default new Cart()
// overlay.js
import $ from 'lib/jquery';
function Overlay() { }
export default new Overlay()
- Future proof
- Nice, compact syntax
- Static module structure
- Live bindings
- Asynchronous / synchronous loading
ES6 Modules
- Still new
- Build tools required
- Module Loader spec
Pros
Cons
Thanks!
JavaScript Module Strategies
By webguyian
JavaScript Module Strategies
- 783