SlideShare a Scribd company logo
JavaScript Modules
by Ivan Sirosh
JavaScript module pattern:
How to create it and why?
Approach to building large
applications
Module pattern requires understanding
modules as a system
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="/public/css/main.css">
</head>
<body>
<div id="content">
</div>
<script src="/public/js/libs/lib1.js"></script>
<script src="/public/js/libs/lib2.js"></script>
<script src="/public/js/libs/lib3.js"></script>
<script src="/module1.js"></script>
<script src="/module2.js"></script>
<script src="/app.js"></script>
</body>
</html>
This is how it’s usually done
var Module = {
a: 1,
b: function() {
//do something
}
};
Correct ****** pattern
(function () {
var a = 1;
function b(){
//do something
}
}());
Import of global variables
(function ($, YUI) {
$.each([1,2,3,4,5], function(){
//do something
});
var Y = YUI();
Y.use('node', function(Y){
//do something
});
}(jQuery, YUI));
Import of local variables
(function(awesome) {
var a;
awesome.splash(function() {
a = 1;
});
waterPool.set("new", function() {
return a;
});
} (waterPool.get("awesome")));
Export of the module
var MODULE = (function () {
var my = {},
privateVariable = 1;
function privateMethod() {
// do something
}
my.moduleProperty = 1;
my.moduleMethod = function () {
// do something
};
return my;
}());
Module extension if the module
doesn't exist
var MODULE = (function (my) {
my.anotherMethod = function () {
// do something
};
return my;
}(MODULE || {}));
We’re done here*
* almost done
Let's look at 3 types of solutions
The bad one
pure JS
var _modules = [];
_modules[0] = function(p){
//do something
};
_modules[1] = [];
_modules[1][0] = 1;
_modules[0](_modules[1][0]);
The ugly one –
Why reinvent the wheel?
pure JS
(function () {
var $ = this.jQuery;
this.myExample = function () {};
}());
The good one
AMD api
define(['jquery'] , function () {
return jQuery;
});
require(['jquery'] , function ($) {
console.log($.now());
});
Require JS
RequireJS is a JavaScript file and module loader. It is
optimized for in-browser use, but it can be used in other
JavaScript environments, like Rhino and Node. Using a
modular script loader like RequireJS will improve the speed
and quality of your code.
IE 6+ .......... compatible ✔
Firefox 2+ ..... compatible ✔
Safari 3.2+ .... compatible ✔
Chrome 3+ ...... compatible ✔
Opera 10+ ...... compatible ✔
http://requirejs.org
Almond JS
A replacement AMD loader for RequireJS. It is a smaller "shim"
loader, providing the minimal AMD API footprint that includes
loader plugin support.
What is supported:
• dependencies with relative IDs.
• define('id', {}) definitions.
• define(), require() and requirejs() calls.
https://github.com/jrburke/almond
AMD
The Asynchronous Module Definition
https://github.com/amdjs/amdjs-api/wiki/AMD
define(id, dependencies, factory);
require(dependencies, callback);
define
define('a-module', function () {
return 'a-module';
});
define('b-module', function () {
return 'b-module';
});
define('c-module', ['a-module', 'b-module'] function (a, b) {
return a + ' ' + b + ' ' + 'c-module';
});
require
require(['c-module'], function (c_module) {
if(c_module){
console.log(c_module)
}
});
a-module b-module c-module
define("alpha", ["require", "exports", "beta"], function(require, exports, beta) {
exports.verb = function() {
return beta.verb();
//Or:
return require("beta").verb();
}
});
define(["alpha"], function(alpha) {
return {
verb: function() {
return alpha.verb() + 2;
}
};
});
define({
add: function(x, y) {
return x + y;
}
});
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define('my-awesome-module', [], factory);
} else {
root.MyAwesomeModule = factory();
}
}(this, function() {
var MyAwesomeModule = function() {};
return new MyAwesomeModule();
}));
If AMD JS isn't implemented,
modules can look as follows
jQuery example done already in the
new version which support AMD
(function(global, factory) {
if (typeof module === "object" && typeof module.exports === "object") {
module.exports = global.document ? factory(global, true) : function(w) {
if (!w.document) {
throw new Error("jQuery requires a window with a document");
}
return factory(w);
};
} else {
factory(global);
}
}(typeof window !== "undefined" ? window : this, function(window, noGlobal) {
var jQuery;
/*-----------------------------------*/
/* ...
/* extend jQuery oject
/* ...
/*-----------------------------------*/
return jQuery;
}));
Don't reinvent the wheel – just use it smartly ;)
JS Modules

More Related Content

KEY
CommonJS Everywhere (Wakanday 2011)
PPTX
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
PDF
Workshop 2: JavaScript Design Patterns
PPSX
RequireJS
PPT
Managing JavaScript Dependencies With RequireJS
PDF
Workshop 16: EmberJS Parte I
PDF
Modularize JavaScript with RequireJS
PDF
Using RequireJS for Modular JavaScript Code
CommonJS Everywhere (Wakanday 2011)
Asynchronous Module Definition (AMD) used for Dependency Injection (DI) and MVVM
Workshop 2: JavaScript Design Patterns
RequireJS
Managing JavaScript Dependencies With RequireJS
Workshop 16: EmberJS Parte I
Modularize JavaScript with RequireJS
Using RequireJS for Modular JavaScript Code

What's hot (20)

PDF
AngularJS 101 - Everything you need to know to get started
PDF
Require.JS
KEY
Requirejs
PDF
React 소개 및 구현방법 Demo
PPTX
Javascript Design Patterns
PPTX
Workshop Intro: FrontEnd General Overview
PDF
Angularjs architecture
PDF
Modern Web Application Development Workflow - EclipseCon Europe 2014
PPTX
Dom selecting & jQuery
PPTX
Require js
PDF
Java Web Programming [7/9] : Struts2 Basics
PPTX
Asp.net MVC - Course 2
PDF
An Introduction To Testing In AngularJS Applications
PDF
Dependency Management with RequireJS
PPTX
Step by Step - AngularJS
PDF
JavaScript Modules Done Right
PDF
Develop plugin for Mozilla Firefox and structure a JS-based application
PDF
Workshop 9: BackboneJS y patrones MVC
PDF
Handlebars and Require.js
AngularJS 101 - Everything you need to know to get started
Require.JS
Requirejs
React 소개 및 구현방법 Demo
Javascript Design Patterns
Workshop Intro: FrontEnd General Overview
Angularjs architecture
Modern Web Application Development Workflow - EclipseCon Europe 2014
Dom selecting & jQuery
Require js
Java Web Programming [7/9] : Struts2 Basics
Asp.net MVC - Course 2
An Introduction To Testing In AngularJS Applications
Dependency Management with RequireJS
Step by Step - AngularJS
JavaScript Modules Done Right
Develop plugin for Mozilla Firefox and structure a JS-based application
Workshop 9: BackboneJS y patrones MVC
Handlebars and Require.js
Ad

Similar to JavaScript Modules in Practice (20)

PDF
Asynchronous Module Definition (AMD)
PDF
JavaScript Dependencies, Modules & Browserify
PDF
Modular JavaScript
PDF
Module, AMD, RequireJS
PDF
Advanced Node.JS Meetup
KEY
Modules and EmbedJS
PDF
Require js training
PDF
Moving to modules
PDF
IOC + Javascript
PDF
Modular JavaScript
PDF
PLOG - Modern Javascripting with Plone
PDF
npm: Modularizing your JavaScript development
PPTX
uRequire@greecejs: An introduction to http://uRequire.org
ODP
Javascript Update May 2013
PPTX
Javascript first-class citizenery
PDF
Introduction to JavaScript design patterns
PDF
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
PDF
System webpack-jspm
PDF
Requirejs
PDF
Modular and Event-Driven JavaScript
Asynchronous Module Definition (AMD)
JavaScript Dependencies, Modules & Browserify
Modular JavaScript
Module, AMD, RequireJS
Advanced Node.JS Meetup
Modules and EmbedJS
Require js training
Moving to modules
IOC + Javascript
Modular JavaScript
PLOG - Modern Javascripting with Plone
npm: Modularizing your JavaScript development
uRequire@greecejs: An introduction to http://uRequire.org
Javascript Update May 2013
Javascript first-class citizenery
Introduction to JavaScript design patterns
DownTheRabbitHole.js – How to Stay Sane in an Insane Ecosystem
System webpack-jspm
Requirejs
Modular and Event-Driven JavaScript
Ad

Recently uploaded (20)

PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
System and Network Administraation Chapter 3
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Nekopoi APK 2025 free lastest update
PDF
Understanding Forklifts - TECH EHS Solution
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
medical staffing services at VALiNTRY
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
top salesforce developer skills in 2025.pdf
PDF
System and Network Administration Chapter 2
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PPTX
Operating system designcfffgfgggggggvggggggggg
PPT
Introduction Database Management System for Course Database
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Odoo Companies in India – Driving Business Transformation.pdf
System and Network Administraation Chapter 3
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Nekopoi APK 2025 free lastest update
Understanding Forklifts - TECH EHS Solution
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Navsoft: AI-Powered Business Solutions & Custom Software Development
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
medical staffing services at VALiNTRY
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
top salesforce developer skills in 2025.pdf
System and Network Administration Chapter 2
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
ManageIQ - Sprint 268 Review - Slide Deck
Operating system designcfffgfgggggggvggggggggg
Introduction Database Management System for Course Database

JavaScript Modules in Practice

  • 2. JavaScript module pattern: How to create it and why?
  • 3. Approach to building large applications
  • 4. Module pattern requires understanding modules as a system <!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="/public/css/main.css"> </head> <body> <div id="content"> </div> <script src="/public/js/libs/lib1.js"></script> <script src="/public/js/libs/lib2.js"></script> <script src="/public/js/libs/lib3.js"></script> <script src="/module1.js"></script> <script src="/module2.js"></script> <script src="/app.js"></script> </body> </html>
  • 5. This is how it’s usually done var Module = { a: 1, b: function() { //do something } };
  • 6. Correct ****** pattern (function () { var a = 1; function b(){ //do something } }());
  • 7. Import of global variables (function ($, YUI) { $.each([1,2,3,4,5], function(){ //do something }); var Y = YUI(); Y.use('node', function(Y){ //do something }); }(jQuery, YUI));
  • 8. Import of local variables (function(awesome) { var a; awesome.splash(function() { a = 1; }); waterPool.set("new", function() { return a; }); } (waterPool.get("awesome")));
  • 9. Export of the module var MODULE = (function () { var my = {}, privateVariable = 1; function privateMethod() { // do something } my.moduleProperty = 1; my.moduleMethod = function () { // do something }; return my; }());
  • 10. Module extension if the module doesn't exist var MODULE = (function (my) { my.anotherMethod = function () { // do something }; return my; }(MODULE || {}));
  • 11. We’re done here* * almost done
  • 12. Let's look at 3 types of solutions
  • 13. The bad one pure JS var _modules = []; _modules[0] = function(p){ //do something }; _modules[1] = []; _modules[1][0] = 1; _modules[0](_modules[1][0]);
  • 14. The ugly one – Why reinvent the wheel? pure JS (function () { var $ = this.jQuery; this.myExample = function () {}; }());
  • 15. The good one AMD api define(['jquery'] , function () { return jQuery; }); require(['jquery'] , function ($) { console.log($.now()); });
  • 16. Require JS RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code. IE 6+ .......... compatible ✔ Firefox 2+ ..... compatible ✔ Safari 3.2+ .... compatible ✔ Chrome 3+ ...... compatible ✔ Opera 10+ ...... compatible ✔ http://requirejs.org
  • 17. Almond JS A replacement AMD loader for RequireJS. It is a smaller "shim" loader, providing the minimal AMD API footprint that includes loader plugin support. What is supported: • dependencies with relative IDs. • define('id', {}) definitions. • define(), require() and requirejs() calls. https://github.com/jrburke/almond
  • 18. AMD The Asynchronous Module Definition https://github.com/amdjs/amdjs-api/wiki/AMD define(id, dependencies, factory); require(dependencies, callback);
  • 19. define define('a-module', function () { return 'a-module'; }); define('b-module', function () { return 'b-module'; }); define('c-module', ['a-module', 'b-module'] function (a, b) { return a + ' ' + b + ' ' + 'c-module'; });
  • 20. require require(['c-module'], function (c_module) { if(c_module){ console.log(c_module) } }); a-module b-module c-module
  • 21. define("alpha", ["require", "exports", "beta"], function(require, exports, beta) { exports.verb = function() { return beta.verb(); //Or: return require("beta").verb(); } });
  • 22. define(["alpha"], function(alpha) { return { verb: function() { return alpha.verb() + 2; } }; }); define({ add: function(x, y) { return x + y; } });
  • 23. (function(root, factory) { if (typeof define === 'function' && define.amd) { define('my-awesome-module', [], factory); } else { root.MyAwesomeModule = factory(); } }(this, function() { var MyAwesomeModule = function() {}; return new MyAwesomeModule(); })); If AMD JS isn't implemented, modules can look as follows
  • 24. jQuery example done already in the new version which support AMD (function(global, factory) { if (typeof module === "object" && typeof module.exports === "object") { module.exports = global.document ? factory(global, true) : function(w) { if (!w.document) { throw new Error("jQuery requires a window with a document"); } return factory(w); }; } else { factory(global); } }(typeof window !== "undefined" ? window : this, function(window, noGlobal) { var jQuery; /*-----------------------------------*/ /* ... /* extend jQuery oject /* ... /*-----------------------------------*/ return jQuery; }));
  • 25. Don't reinvent the wheel – just use it smartly ;) JS Modules