SlideShare a Scribd company logo
1 of 95
Download to read offline
JavaScript Modules
Done right
Client & server-side code organization




                            meetjs · November 2011 · Warsaw, Poland
Mariusz Nowak
mariusz@medikoo.com



   @medikoo


   github.com/medikoo


JavaScript Programmer at Roche Ltd.
Browser
In the beginning there was Browser.
How we managed large code bases (?)
Browser
In the beginning there was Browser.
How we managed large code bases (?)

• Files concatenation
Browser
Written usually this style:
MAIN.module = (function() {
    var privateVar = '..';

   var privateMethod = function (args) {
       // ...
   };

   return {
       publicProperty: '..',
       publicMethod: function () {
           // ...
       }
   };

}());
Browser
In the beginning there was Browser.
How we managed large code bases (?)

• Files concatenation
Browser
In the beginning there was Browser.
How we managed large code bases (?)

• Files concatenation
• Module pattern
Server
Beginning of 2009
• Growing number of interpreters: Rhino, Spidermonkey, V8, JSCore
• No cross-interpreter standards
• There are programmers who want to write server-side JavaScript but
want to have their code runnable on any engine
Server
Beginning of 2009
• Growing number of interpreters: Rhino, Spidermonkey, V8, JSCore
• No cross-interpreter standards
• There are programmers who want to write server-side JavaScript but
want to have their code runnable on any engine
• There’s a need for standard library API that would allow JavaScript
ecosystem grow (as it happened for Ruby, Python or Java)
Server
Beginning of 2009
• Growing number of interpreters: Rhino, Spidermonkey, V8, JSCore
• No cross-interpreter standards
• There are programmers who want to write server-side JavaScript but
want to have their code runnable on any engine
• There’s a need for standard library API that would allow JavaScript
ecosystem grow (as it happened for Ruby, Python or Java)
• ServerJS initiative is announced, renamed later into CommonJS
-> http://www.blueskyonmars.com/2009/01/29/what-server-side-javascript-needs/
Server
CommonJS presents Modules specification ->
http://www.commonjs.org/specs/modules/1.0/
Server
CommonJS presents Modules specification ->
http://www.commonjs.org/specs/modules/1.0/

add.js
exports.add = function() {
     var sum = 0, i = 0, args = arguments, l = args.length;
     while (i < l) sum += args[i++];
     return sum;
};

increment.js
var add = require('add').add;
exports.increment = function(val) {
     return add(val, 1);
};

program.js
var inc = require('increment').increment;
var a = 1;
inc(a); // 2
Server
In about same time Ryan Dahl creates Node.js, which
implements CommonJS Modules

add.js
exports.add = function() {
     var sum = 0, i = 0, args = arguments, l = args.length;
     while (i < l) sum += args[i++];
     return sum;
};

increment.js
var add = require('add').add;
exports.increment = function(val) {
     return add(val, 1);
};

program.js
var inc = require('increment').increment;
var a = 1;
inc(a); // 2
Server
In about same time Ryan Dahl creates Node.js, which
implements CommonJS Modules
... with some improvements
add.js
module.exports = function() {
     var sum = 0, i = 0, args = arguments, l = args.length;
     while (i < l) sum += args[i++];
     return sum;
};

increment.js
var add = require('./add');
module.exports = function(val) {
     return add(val, 1);
};

program.js
var inc = require('./increment');
var a = 1;
inc(a); // 2
Server
How module works:



  // increment.js
  var add = require('./add');
  module.exports = function (val) {
      return add(val, 1);
  };
Server
How module works:
var exports, module;
function (exports, require, module) {

   // increment.js
   var add = require('./add');
   module.exports = function (val) {
       return add(val, 1);
   };

}.call(exports = {}, exports, function (path) {
 // import external module
}, module = { exports: exports });

MODULE = module.exports;
Server
Let’s get back to module pattern.
Server
Let’s get back to module pattern.
module.js
MAIN.module = (function() {
    var privateVar = '..';
    var privateMethod = function (args) {
        // ...
    };
    return {
        publicProperty: '..',
        publicMethod: function () {
            // ...
        }
    };
}());
Server
Module pattern as CommonJS module:
module.js

var privateVar = '..';
var privateMethod = function (args) {
    // ...
};

exports.publicProperty: '..',
exports.publicMethod: function () {
    // ...
};

program.js
var foobar = require(‘./module’);
Server
Module pattern as CommonJS module:
module.js

var privateVar = '..';
var privateMethod = function (args) {
    // ...
};

exports.publicProperty: '..',
exports.publicMethod: function () {
    // ...
};

program.js
var foobar = require(‘./module’);
    ↑ we decide locally under which name we’ll access imported module
Server
CommonJS Modules is indeed great specification.
What are the benefits ?
Server
CommonJS Modules is indeed great specification.
What are the benefits ?

First of all, cleanliness and encapsulation on highest
available (for JavaScript) level
Server
CommonJS Modules is indeed great specification.
What are the benefits ?

First of all, cleanliness and encapsulation on highest
available (for JavaScript) level

• There’s no need to write obsolete function wrappers to work in private
scope
Server
CommonJS Modules is indeed great specification.
What are the benefits ?

First of all, cleanliness and encapsulation on highest
available (for JavaScript) level

• There’s no need to write obsolete function wrappers to work in private
scope
• We don’t have to deal with long namespaces, each required module is
assigned to local variable
Server
CommonJS Modules is indeed great specification.
What are the benefits ?

First of all, cleanliness and encapsulation on highest
available (for JavaScript) level

• There’s no need to write obsolete function wrappers to work in private
scope
• We don’t have to deal with long namespaces, each required module is
assigned to local variable
• We can build large complex application without a need to touch global
namespace
Server & Browser
How to run it in the Browser ?
Server & Browser
How to run it in the Browser ?

When I started working with CommonJS and Node.js
(beginning 2011) I thought there’s solid solution already
available
Server & Browser
How to run it in the Browser ?

When I started working with CommonJS and Node.js
(beginning 2011) I thought there’s solid solution already
available

I’ve found about 8-10 solutions that aimed at something
similar, however none of them were really working right
Server & Browser
Main issue was that each of them, was trying to be
something more than Node.js modules parser, and “more”
seemed to have more attention than dependency parser I
was after.
Server & Browser
Main issue was that each of them, was trying to be
something more than Node.js modules parser, and “more”
seemed to have more attention than dependency parser I
was after.

Parsers were incomplete and buggy
Server & Browser
Anyway, time goes by, there are few solutions that
deserve focus
Server & Browser
Anyway, time goes by, there are few solutions that
deserve focus

Browserify -> https://github.com/substack/node-browserify
Server & Browser
Anyway, time goes by, there are few solutions that
deserve focus

Browserify -> https://github.com/substack/node-browserify

Very interesting tool, if we’re after reusing native Node.js modules on
client-side. Browserify struggles to make it possible, I guess it was main
intention behind the project.
Server & Browser
Anyway, time goes by, there are few solutions that
deserve focus

Browserify -> https://github.com/substack/node-browserify

Very interesting tool, if we’re after reusing native Node.js modules on
client-side. Browserify struggles to make it possible, I guess it was main
intention behind the project.

You need to add extra 320 lines of code for client-side to make it work,
that’s not impressive, this code could be much smaller.
Server & Browser
Anyway, time goes by, there are few solutions that
deserve focus

Browserify -> https://github.com/substack/node-browserify

Very interesting tool, if we’re after reusing native Node.js modules on
client-side. Browserify struggles to make it possible, I guess it was main
intention behind the project.

You need to add extra 320 lines of code for client-side to make it work,
that’s not impressive, this code could be much smaller.

It doesn’t work well with some paths, modules from external packages
were not found when I played with that (not sure if it’s bug or limitation)
Server & Browser
AMD -> Asynchronous Module Definition
Server & Browser
AMD -> Asynchronous Module Definition

It gained some attention lately:

http://addyosmani.com/writing-modular-js/

http://blog.millermedeiros.com/2011/09/amd-is-better-for-the-web-than-commonjs-
modules/

http://unscriptable.com/index.php/2011/09/30/amd-versus-cjs-whats-the-best-
format/
Server & Browser
AMD ?
Server & Browser
AMD ?
It was made for browsers - Node.js won’t run AMD module properly
Server & Browser
AMD ?
It was made for browsers - Node.js won’t run AMD module properly
Server & Browser
AMD ?
It was made for browsers - Node.js won’t run AMD module properly

AMD has not much to do with CommonJS Modules, you need to
write modules differently
Server & Browser
AMD ?
It was made for browsers - Node.js won’t run AMD module properly

AMD has not much to do with CommonJS Modules, you need to
write modules differently

• All dependencies needs to be declared at begin of module
Server & Browser
AMD ?
It was made for browsers - Node.js won’t run AMD module properly

AMD has not much to do with CommonJS Modules, you need to
write modules differently

• All dependencies needs to be declared at begin of module
In CommonJS we can reach for external modules in any place at any time, and it’s
same for native modules that JavaScript will have in a future.
Server & Browser
AMD ?
It was made for browsers - Node.js won’t run AMD module properly

AMD has not much to do with CommonJS Modules, you need to
write modules differently

• All dependencies needs to be declared at begin of module
In CommonJS we can reach for external modules in any place at any time, and it’s
same for native modules that JavaScript will have in a future.

• Again, we need to use function wrappers. Each module needs to be declared with
function call
Server & Browser
Why is that ?
Server & Browser
Why is that ?

AMD tries to be solution for two problems:

• Code modularization and organization
• Dynamic dependency handling, so we load only that
code that is actually used
Server & Browser
Why is that ?

AMD tries to be solution for two problems:

• Code modularization and organization
• Dynamic dependency handling, so we load only that
code that is actually used

Sounds promising, but is it worth it ?
Server & Browser
How AMD modules look like ?
Server & Browser
How AMD modules look like ?
add.js
define(function () {
     return function() {
          var sum = 0, i = 0, args = arguments, l = args.length;
          while (i < l) sum += args[i++];
          return sum;
     };
});

increment.js
define(['add'], function (add) {
     return function(val) {
          return add(val, 1);
     };
});

program.js
define(['increment'], function (inc) {
     var a = 1;
     inc(a); // 2
});
Server & Browser
Most popular implementation -> http://requirejs.org/
requires us to load library made of 2000 lines of code.
Server & Browser
Most popular implementation -> http://requirejs.org/
requires us to load library made of 2000 lines of code.

... it’s needed just to run code of our application.
Server & Browser
Most popular implementation -> http://requirejs.org/
requires us to load library made of 2000 lines of code.

... it’s needed just to run code of our application.

... and still we cannot use our modules on server-side
(Node.js) without extra compilation step.
Server & Browser
Ok, but what about dynamic dependency resolution, isn’t it
main purpose of AMD ?
Server & Browser
Ok, but what about dynamic dependency resolution, isn’t it
main purpose of AMD ?


In my opinion dynamic dependency resolution should be
considered on application functionality level not on
modules level
Server & Browser
Summary:
Server & Browser
Summary:

We miss light and clean CommonJS (precisely Node.js) Modules
implementation, that would allow us to use them on client side
Server & Browser
Summary:

We miss light and clean CommonJS (precisely Node.js) Modules
implementation, that would allow us to use them on client side

Implementation that wouldn’t try to be solution for other
problems in first place.
Server & Browser
Summary:

We miss light and clean CommonJS (precisely Node.js) Modules
implementation, that would allow us to use them on client side

Implementation that wouldn’t try to be solution for other
problems in first place.

Code for handling modules on client side should be minimal,
unnoticeable in size when compared to application code
Server & Browser
Finally new project was born:
Server & Browser
Finally new project was born:

modules-webmake ->
https://github.com/medikoo/modules-webmake

npm install -g webmake
Modules Webmake
modules-webmake scans modules, builds dependency tree and
produces output that it executable in the browser
Modules Webmake
modules-webmake scans modules, builds dependency tree and
produces output that it executable in the browser

Current implementation is very basic, we might say, we just started
Modules Webmake
modules-webmake scans modules, builds dependency tree and
produces output that it executable in the browser

Current implementation is very basic, we might say, we just started

It doesn’t limit us though from building complex applications made
from hundreds of modules that originated from dozens of packages
Modules Webmake
modules-webmake scans modules, builds dependency tree and
produces output that it executable in the browser

Current implementation is very basic, we might say, we just started

It doesn’t limit us though from building complex applications made
from hundreds of modules that originated from dozens of packages

With modules-webmake you can build complex applications, right
now
Modules Webmake
How generated file looks like ?
Modules Webmake
How generated file looks like ?
(function (modules) {
     // 53 lines of import/export logic
})
({
     "root": {
          "add.js": function (exports, module, require) {
               module.exports = function () {
                    var sum = 0, i = 0, args = arguments, l = args.length;
                    while (i < l) sum += args[i++];
                    return sum;
               };
          },
          "increment.js": function (exports, module, require) {
               var add = require('./add');
               module.exports = function (val) {
                    return add(val, 1);
               };
          },
          "program.js": function (exports, module, require) {
               var inc = require('./increment');
               var a = 1;
               inc(a); // 2
          }
     }
})
("root/program");
Modules Webmake
How generated file looks like ?
(function (modules) {
     // 53 lines of import/export logic
})
({
     "root": {
          "add.js": function (exports, module, require) {
               module.exports = function () {
                    var sum = 0, i = 0, args = arguments, l = args.length;
                    while (i < l) sum += args[i++];
                    return sum;
               };
          },
          "increment.js": function (exports, module, require) {
               var add = require('./add');
               module.exports = function (val) {
                    return add(val, 1);
               };
          },
          "program.js": function (exports, module, require) {
               var inc = require('./increment');
               var a = 1;
               inc(a); // 2
          }
     }
})
("root/program"); <- Execution of module that initiates application
Modules Webmake
• modules-webmake can be used both from shell and programmatically - we can
bind it to http server in Node.js and generate files on demand
Modules Webmake
• modules-webmake can be used both from shell and programmatically - we can
bind it to http server in Node.js and generate files on demand

• Dependencies are parsed statically, it introduces some limitations, for specific
cases we may force inclusion of chosen modules with ‘include’ option.
Modules Webmake
• modules-webmake can be used both from shell and programmatically - we can
bind it to http server in Node.js and generate files on demand

• Dependencies are parsed statically, it introduces some limitations, for specific
cases we may force inclusion of chosen modules with ‘include’ option.

• modules-webmake reads local dependencies and those from external packages,
one limitation is that it doesn’t recognize two different versions of same package (it
will be addressed)
Modules Webmake
• modules-webmake can be used both from shell and programmatically - we can
bind it to http server in Node.js and generate files on demand

• Dependencies are parsed statically, it introduces some limitations, for specific
cases we may force inclusion of chosen modules with ‘include’ option.

• modules-webmake reads local dependencies and those from external packages,
one limitation is that it doesn’t recognize two different versions of same package (it
will be addressed)

• Up to date documentation can be found at github project page:
https://github.com/medikoo/modules-webmake
Modules Webmake
Last week I finished work on application that was built with help of
modules-webmake.


• It’s HTML5 application, targetted only for modern browsers (newest FF, Chrome and
Safari (both OSX & iOS))

• To support Offline mode we needed to put whole application logic to client side,
including templates and simple database engine.

• Node.js on server-side, takes care about clients synchronization and saving data to
physical database (mongodb)

• Minimalistic client-server communication based on sockets (Socket.IO)
Modules Webmake
Final JavaScript file for client consists of 273 modules from 19 packages.

176 of mentioned modules works also on server side.
It means that about 60% of client-side code is also running on server-side.

Concatenated file is 11 thousand lines long
and weights about 370kB before minification and zipping.

It looks quite promising, if we take into account, that it consists of templates for
whole application and all other modules that application is made of, including simple
database engine.

After application load, all client-server communication is minimal as all pages as
generated by client.
Modules Webmake
Upcoming improvements:
Modules Webmake
Upcoming improvements:

• Not only parser, but full modules engine. What for? It will allow to run and test
modules with it’s dependencies in differently setup environments, like pure V8 +
Modules, or emulation of browser environment.
Modules Webmake
Upcoming improvements:

• Not only parser, but full modules engine. What for? It will allow to run and test
modules with it’s dependencies in differently setup environments, like pure V8 +
Modules, or emulation of browser environment.
• Work in a background, it will allow much more optimized and faster file generation
(watching file system for changes, immediate serving of generated files when
integrated with node.js http server)
Modules Webmake
Upcoming improvements:

• Not only parser, but full modules engine. What for? It will allow to run and test
modules with it’s dependencies in differently setup environments, like pure V8 +
Modules, or emulation of browser environment.
• Work in a background, it will allow much more optimized and faster file generation
(watching file system for changes, immediate serving of generated files when
integrated with node.js http server)
• Optional minification, compilation
Modules Webmake
Upcoming improvements:

• Not only parser, but full modules engine. What for? It will allow to run and test
modules with it’s dependencies in differently setup environments, like pure V8 +
Modules, or emulation of browser environment.
• Work in a background, it will allow much more optimized and faster file generation
(watching file system for changes, immediate serving of generated files when
integrated with node.js http server)
• Optional minification, compilation
• Discovering modules that were required but not used
Modules Webmake
Upcoming improvements:

• Not only parser, but full modules engine. What for? It will allow to run and test
modules with it’s dependencies in differently setup environments, like pure V8 +
Modules, or emulation of browser environment.
• Work in a background, it will allow much more optimized and faster file generation
(watching file system for changes, immediate serving of generated files when
integrated with node.js http server)
• Optional minification, compilation
• Discovering modules that were required but not used
• Splitting into few files (for faster client-side load)
Modules Webmake
Upcoming improvements:

• Not only parser, but full modules engine. What for? It will allow to run and test
modules with it’s dependencies in differently setup environments, like pure V8 +
Modules, or emulation of browser environment.
• Work in a background, it will allow much more optimized and faster file generation
(watching file system for changes, immediate serving of generated files when
integrated with node.js http server)
• Optional minification, compilation
• Discovering modules that were required but not used
• Splitting into few files (for faster client-side load)
• Modules should not be duplicated in different files, introduction of intelligent more
than one file generation
Modules Webmake
Upcoming improvements:

• Not only parser, but full modules engine. What for? It will allow to run and test
modules with it’s dependencies in differently setup environments, like pure V8 +
Modules, or emulation of browser environment.
• Work in a background, it will allow much more optimized and faster file generation
(watching file system for changes, immediate serving of generated files when
integrated with node.js http server)
• Optional minification, compilation
• Discovering modules that were required but not used
• Splitting into few files (for faster client-side load)
• Modules should not be duplicated in different files, introduction of intelligent more
than one file generation
• Small code fixes for buggy engines e.g. quoting reserved keywords used as
property names
Future: Harmony
We will have modules natively in JavaScript

http://wiki.ecmascript.org/doku.php?id=harmony:modules_examples
Future: Harmony
We will have modules natively in JavaScript

http://wiki.ecmascript.org/doku.php?id=harmony:modules_examples


Base concept of Harmony Modules is same as in
CommonJS Modules.
Future: Harmony
We will have modules natively in JavaScript

http://wiki.ecmascript.org/doku.php?id=harmony:modules_examples


Base concept of Harmony Modules is same as in
CommonJS Modules.

Differences lies in dedicated syntax, and powerful
optional features like dynamic loading, possibility to load
external modules via url etc.
Harmony Modules
Harmony Modules
What we currently write for Node.js:
add.js
module.exports = function() {
     var sum = 0, i = 0, args = arguments, l = args.length;
     while (i < l) sum += args[i++];
     return sum;
};

increment.js
var add = require('./add');
module.exports = function(val) {
     return add(val, 1);
};

program.js
var inc = require('./increment');
var a = 1;
inc(a); // 2
Harmony Modules
Will be written that way with Harmony:
add.js
export function add () {
     var sum = 0, i = 0, args = arguments, l = args.length;
     while (i < l) sum += args[i++];
     return sum;
};

increment.js
import add from './add';
export function increment (val) {
     return add(val, 1);
};

program.js
import { increment: inc } from './increment';
var a = 1;
inc(a); // 2
Harmony Modules
Modules Webmake for EcmaScript 3/5:
(function (modules) {
     // 53 lines of import/export logic
})
({
     "root": {
          "add.js": function (exports, module, require) {
               module.exports = function () {
                    var sum = 0, i = 0, args = arguments, l = args.length;
                    while (i < l) sum += args[i++];
                    return sum;
               };
          },
          "increment.js": function (exports, module, require) {
               var add = require('./add');
               module.exports = function (val) {
                    return add(val, 1);
               };
          },
          "program.js": function (exports, module, require) {
               var inc = require('./increment');
               var a = 1;
               inc(a); // 2
          }
     }
})
("root/program");
Harmony Modules
Modules Webmake for Harmony:



         module add {
              export function add () {
                   var sum = 0, i = 0, args = arguments, l = args.length;
                   while (i < l) sum += args[i++];
                   return sum;
              };
         };
         module increment {
              import add from add;
              export function increment (val) {
                   return add(val, 1);
              };
         };
         module program {
              import { increment: inc } from increment;
              var a = 1;
              inc(a); // 2
         };


import * from program;
Server & Browser

If you use CommonJS/Node.js Modules today, it won’t be
problematic for you to switch to Harmony in few years
time
Server & Browser

If you use CommonJS/Node.js Modules today, it won’t be
problematic for you to switch to Harmony in few years
time


Today:
CommonJS/Node.js Modules & modules-webmake
Server & Browser

If you use CommonJS/Node.js Modules today, it won’t be
problematic for you to switch to Harmony in few years
time


Today:
CommonJS/Node.js Modules & modules-webmake


Tomorrow:
Harmony Modules
Server & Browser

If you use CommonJS/Node.js Modules today, it won’t be
problematic for you to switch to Harmony in few years
time


Today:
CommonJS/Node.js Modules & modules-webmake


Tomorrow:
Harmony Modules (& modules-webmake ?)
Questions ?
Thank You !

Mariusz Nowak
mariusz@medikoo.com



   @medikoo


   github.com/medikoo

More Related Content

What's hot

JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesDoris Chen
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJWORKS powered by Ordina
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureNicholas Zakas
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture Jiby John
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Jaroslaw Palka
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MySteve McMahon
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScriptCodemotion
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Aaron Gustafson
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practicesSultan Khan
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 

What's hot (20)

JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Performance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best PracticesPerformance Optimization and JavaScript Best Practices
Performance Optimization and JavaScript Best Practices
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture jQquerysummit - Large-scale JavaScript Application Architecture
jQquerysummit - Large-scale JavaScript Application Architecture
 
Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014Patterns for JVM languages - Geecon 2014
Patterns for JVM languages - Geecon 2014
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh My
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScript
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]Fundamental JavaScript [In Control 2009]
Fundamental JavaScript [In Control 2009]
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
Javascript
JavascriptJavascript
Javascript
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 

Similar to JavaScript Modules Done Right

Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.jsChris Cowan
 
JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An IntroductionNirvanic Labs
 
uRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.orguRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.orgAgelos Pikoulas
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS MeetupLINAGORA
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteorSapna Upreti
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
Introduction to node.js by jiban
Introduction to node.js by jibanIntroduction to node.js by jiban
Introduction to node.js by jibanJibanananda Sana
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS偉格 高
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Modules and EmbedJS
Modules and EmbedJSModules and EmbedJS
Modules and EmbedJSJens Arps
 
Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...Lucas Jellema
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...Paul Jensen
 
Google App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGoogle App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGuillaume Laforge
 
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...Malin Weiss
 
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...Speedment, Inc.
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 

Similar to JavaScript Modules Done Right (20)

Intro To Node.js
Intro To Node.jsIntro To Node.js
Intro To Node.js
 
JS & NodeJS - An Introduction
JS & NodeJS - An IntroductionJS & NodeJS - An Introduction
JS & NodeJS - An Introduction
 
uRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.orguRequire@greecejs: An introduction to http://uRequire.org
uRequire@greecejs: An introduction to http://uRequire.org
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
Introduction to node.js by jiban
Introduction to node.js by jibanIntroduction to node.js by jiban
Introduction to node.js by jiban
 
Module, AMD, RequireJS
Module, AMD, RequireJSModule, AMD, RequireJS
Module, AMD, RequireJS
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Modules and EmbedJS
Modules and EmbedJSModules and EmbedJS
Modules and EmbedJS
 
NodeJS @ ACS
NodeJS @ ACSNodeJS @ ACS
NodeJS @ ACS
 
Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...Introduction to web application development with Vue (for absolute beginners)...
Introduction to web application development with Vue (for absolute beginners)...
 
Node azure
Node azureNode azure
Node azure
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
 
Intro to Sails.js
Intro to Sails.jsIntro to Sails.js
Intro to Sails.js
 
Google App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGoogle App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and Gaelyk
 
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
 
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 

Recently uploaded

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Recently uploaded (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

JavaScript Modules Done Right

  • 1. JavaScript Modules Done right Client & server-side code organization meetjs · November 2011 · Warsaw, Poland
  • 2. Mariusz Nowak mariusz@medikoo.com @medikoo github.com/medikoo JavaScript Programmer at Roche Ltd.
  • 3. Browser In the beginning there was Browser. How we managed large code bases (?)
  • 4. Browser In the beginning there was Browser. How we managed large code bases (?) • Files concatenation
  • 5. Browser Written usually this style: MAIN.module = (function() { var privateVar = '..'; var privateMethod = function (args) { // ... }; return { publicProperty: '..', publicMethod: function () { // ... } }; }());
  • 6. Browser In the beginning there was Browser. How we managed large code bases (?) • Files concatenation
  • 7. Browser In the beginning there was Browser. How we managed large code bases (?) • Files concatenation • Module pattern
  • 8. Server Beginning of 2009 • Growing number of interpreters: Rhino, Spidermonkey, V8, JSCore • No cross-interpreter standards • There are programmers who want to write server-side JavaScript but want to have their code runnable on any engine
  • 9. Server Beginning of 2009 • Growing number of interpreters: Rhino, Spidermonkey, V8, JSCore • No cross-interpreter standards • There are programmers who want to write server-side JavaScript but want to have their code runnable on any engine • There’s a need for standard library API that would allow JavaScript ecosystem grow (as it happened for Ruby, Python or Java)
  • 10. Server Beginning of 2009 • Growing number of interpreters: Rhino, Spidermonkey, V8, JSCore • No cross-interpreter standards • There are programmers who want to write server-side JavaScript but want to have their code runnable on any engine • There’s a need for standard library API that would allow JavaScript ecosystem grow (as it happened for Ruby, Python or Java) • ServerJS initiative is announced, renamed later into CommonJS -> http://www.blueskyonmars.com/2009/01/29/what-server-side-javascript-needs/
  • 11. Server CommonJS presents Modules specification -> http://www.commonjs.org/specs/modules/1.0/
  • 12. Server CommonJS presents Modules specification -> http://www.commonjs.org/specs/modules/1.0/ add.js exports.add = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) sum += args[i++]; return sum; }; increment.js var add = require('add').add; exports.increment = function(val) { return add(val, 1); }; program.js var inc = require('increment').increment; var a = 1; inc(a); // 2
  • 13. Server In about same time Ryan Dahl creates Node.js, which implements CommonJS Modules add.js exports.add = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) sum += args[i++]; return sum; }; increment.js var add = require('add').add; exports.increment = function(val) { return add(val, 1); }; program.js var inc = require('increment').increment; var a = 1; inc(a); // 2
  • 14. Server In about same time Ryan Dahl creates Node.js, which implements CommonJS Modules ... with some improvements add.js module.exports = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) sum += args[i++]; return sum; }; increment.js var add = require('./add'); module.exports = function(val) { return add(val, 1); }; program.js var inc = require('./increment'); var a = 1; inc(a); // 2
  • 15. Server How module works: // increment.js var add = require('./add'); module.exports = function (val) { return add(val, 1); };
  • 16. Server How module works: var exports, module; function (exports, require, module) { // increment.js var add = require('./add'); module.exports = function (val) { return add(val, 1); }; }.call(exports = {}, exports, function (path) { // import external module }, module = { exports: exports }); MODULE = module.exports;
  • 17. Server Let’s get back to module pattern.
  • 18. Server Let’s get back to module pattern. module.js MAIN.module = (function() { var privateVar = '..'; var privateMethod = function (args) { // ... }; return { publicProperty: '..', publicMethod: function () { // ... } }; }());
  • 19. Server Module pattern as CommonJS module: module.js var privateVar = '..'; var privateMethod = function (args) { // ... }; exports.publicProperty: '..', exports.publicMethod: function () { // ... }; program.js var foobar = require(‘./module’);
  • 20. Server Module pattern as CommonJS module: module.js var privateVar = '..'; var privateMethod = function (args) { // ... }; exports.publicProperty: '..', exports.publicMethod: function () { // ... }; program.js var foobar = require(‘./module’); ↑ we decide locally under which name we’ll access imported module
  • 21. Server CommonJS Modules is indeed great specification. What are the benefits ?
  • 22. Server CommonJS Modules is indeed great specification. What are the benefits ? First of all, cleanliness and encapsulation on highest available (for JavaScript) level
  • 23. Server CommonJS Modules is indeed great specification. What are the benefits ? First of all, cleanliness and encapsulation on highest available (for JavaScript) level • There’s no need to write obsolete function wrappers to work in private scope
  • 24. Server CommonJS Modules is indeed great specification. What are the benefits ? First of all, cleanliness and encapsulation on highest available (for JavaScript) level • There’s no need to write obsolete function wrappers to work in private scope • We don’t have to deal with long namespaces, each required module is assigned to local variable
  • 25. Server CommonJS Modules is indeed great specification. What are the benefits ? First of all, cleanliness and encapsulation on highest available (for JavaScript) level • There’s no need to write obsolete function wrappers to work in private scope • We don’t have to deal with long namespaces, each required module is assigned to local variable • We can build large complex application without a need to touch global namespace
  • 26. Server & Browser How to run it in the Browser ?
  • 27. Server & Browser How to run it in the Browser ? When I started working with CommonJS and Node.js (beginning 2011) I thought there’s solid solution already available
  • 28. Server & Browser How to run it in the Browser ? When I started working with CommonJS and Node.js (beginning 2011) I thought there’s solid solution already available I’ve found about 8-10 solutions that aimed at something similar, however none of them were really working right
  • 29. Server & Browser Main issue was that each of them, was trying to be something more than Node.js modules parser, and “more” seemed to have more attention than dependency parser I was after.
  • 30. Server & Browser Main issue was that each of them, was trying to be something more than Node.js modules parser, and “more” seemed to have more attention than dependency parser I was after. Parsers were incomplete and buggy
  • 31. Server & Browser Anyway, time goes by, there are few solutions that deserve focus
  • 32. Server & Browser Anyway, time goes by, there are few solutions that deserve focus Browserify -> https://github.com/substack/node-browserify
  • 33. Server & Browser Anyway, time goes by, there are few solutions that deserve focus Browserify -> https://github.com/substack/node-browserify Very interesting tool, if we’re after reusing native Node.js modules on client-side. Browserify struggles to make it possible, I guess it was main intention behind the project.
  • 34. Server & Browser Anyway, time goes by, there are few solutions that deserve focus Browserify -> https://github.com/substack/node-browserify Very interesting tool, if we’re after reusing native Node.js modules on client-side. Browserify struggles to make it possible, I guess it was main intention behind the project. You need to add extra 320 lines of code for client-side to make it work, that’s not impressive, this code could be much smaller.
  • 35. Server & Browser Anyway, time goes by, there are few solutions that deserve focus Browserify -> https://github.com/substack/node-browserify Very interesting tool, if we’re after reusing native Node.js modules on client-side. Browserify struggles to make it possible, I guess it was main intention behind the project. You need to add extra 320 lines of code for client-side to make it work, that’s not impressive, this code could be much smaller. It doesn’t work well with some paths, modules from external packages were not found when I played with that (not sure if it’s bug or limitation)
  • 36. Server & Browser AMD -> Asynchronous Module Definition
  • 37. Server & Browser AMD -> Asynchronous Module Definition It gained some attention lately: http://addyosmani.com/writing-modular-js/ http://blog.millermedeiros.com/2011/09/amd-is-better-for-the-web-than-commonjs- modules/ http://unscriptable.com/index.php/2011/09/30/amd-versus-cjs-whats-the-best- format/
  • 39. Server & Browser AMD ? It was made for browsers - Node.js won’t run AMD module properly
  • 40. Server & Browser AMD ? It was made for browsers - Node.js won’t run AMD module properly
  • 41. Server & Browser AMD ? It was made for browsers - Node.js won’t run AMD module properly AMD has not much to do with CommonJS Modules, you need to write modules differently
  • 42. Server & Browser AMD ? It was made for browsers - Node.js won’t run AMD module properly AMD has not much to do with CommonJS Modules, you need to write modules differently • All dependencies needs to be declared at begin of module
  • 43. Server & Browser AMD ? It was made for browsers - Node.js won’t run AMD module properly AMD has not much to do with CommonJS Modules, you need to write modules differently • All dependencies needs to be declared at begin of module In CommonJS we can reach for external modules in any place at any time, and it’s same for native modules that JavaScript will have in a future.
  • 44. Server & Browser AMD ? It was made for browsers - Node.js won’t run AMD module properly AMD has not much to do with CommonJS Modules, you need to write modules differently • All dependencies needs to be declared at begin of module In CommonJS we can reach for external modules in any place at any time, and it’s same for native modules that JavaScript will have in a future. • Again, we need to use function wrappers. Each module needs to be declared with function call
  • 45. Server & Browser Why is that ?
  • 46. Server & Browser Why is that ? AMD tries to be solution for two problems: • Code modularization and organization • Dynamic dependency handling, so we load only that code that is actually used
  • 47. Server & Browser Why is that ? AMD tries to be solution for two problems: • Code modularization and organization • Dynamic dependency handling, so we load only that code that is actually used Sounds promising, but is it worth it ?
  • 48. Server & Browser How AMD modules look like ?
  • 49. Server & Browser How AMD modules look like ? add.js define(function () { return function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) sum += args[i++]; return sum; }; }); increment.js define(['add'], function (add) { return function(val) { return add(val, 1); }; }); program.js define(['increment'], function (inc) { var a = 1; inc(a); // 2 });
  • 50. Server & Browser Most popular implementation -> http://requirejs.org/ requires us to load library made of 2000 lines of code.
  • 51. Server & Browser Most popular implementation -> http://requirejs.org/ requires us to load library made of 2000 lines of code. ... it’s needed just to run code of our application.
  • 52. Server & Browser Most popular implementation -> http://requirejs.org/ requires us to load library made of 2000 lines of code. ... it’s needed just to run code of our application. ... and still we cannot use our modules on server-side (Node.js) without extra compilation step.
  • 53. Server & Browser Ok, but what about dynamic dependency resolution, isn’t it main purpose of AMD ?
  • 54. Server & Browser Ok, but what about dynamic dependency resolution, isn’t it main purpose of AMD ? In my opinion dynamic dependency resolution should be considered on application functionality level not on modules level
  • 56. Server & Browser Summary: We miss light and clean CommonJS (precisely Node.js) Modules implementation, that would allow us to use them on client side
  • 57. Server & Browser Summary: We miss light and clean CommonJS (precisely Node.js) Modules implementation, that would allow us to use them on client side Implementation that wouldn’t try to be solution for other problems in first place.
  • 58. Server & Browser Summary: We miss light and clean CommonJS (precisely Node.js) Modules implementation, that would allow us to use them on client side Implementation that wouldn’t try to be solution for other problems in first place. Code for handling modules on client side should be minimal, unnoticeable in size when compared to application code
  • 59. Server & Browser Finally new project was born:
  • 60. Server & Browser Finally new project was born: modules-webmake -> https://github.com/medikoo/modules-webmake npm install -g webmake
  • 61. Modules Webmake modules-webmake scans modules, builds dependency tree and produces output that it executable in the browser
  • 62. Modules Webmake modules-webmake scans modules, builds dependency tree and produces output that it executable in the browser Current implementation is very basic, we might say, we just started
  • 63. Modules Webmake modules-webmake scans modules, builds dependency tree and produces output that it executable in the browser Current implementation is very basic, we might say, we just started It doesn’t limit us though from building complex applications made from hundreds of modules that originated from dozens of packages
  • 64. Modules Webmake modules-webmake scans modules, builds dependency tree and produces output that it executable in the browser Current implementation is very basic, we might say, we just started It doesn’t limit us though from building complex applications made from hundreds of modules that originated from dozens of packages With modules-webmake you can build complex applications, right now
  • 65. Modules Webmake How generated file looks like ?
  • 66. Modules Webmake How generated file looks like ? (function (modules) { // 53 lines of import/export logic }) ({ "root": { "add.js": function (exports, module, require) { module.exports = function () { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) sum += args[i++]; return sum; }; }, "increment.js": function (exports, module, require) { var add = require('./add'); module.exports = function (val) { return add(val, 1); }; }, "program.js": function (exports, module, require) { var inc = require('./increment'); var a = 1; inc(a); // 2 } } }) ("root/program");
  • 67. Modules Webmake How generated file looks like ? (function (modules) { // 53 lines of import/export logic }) ({ "root": { "add.js": function (exports, module, require) { module.exports = function () { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) sum += args[i++]; return sum; }; }, "increment.js": function (exports, module, require) { var add = require('./add'); module.exports = function (val) { return add(val, 1); }; }, "program.js": function (exports, module, require) { var inc = require('./increment'); var a = 1; inc(a); // 2 } } }) ("root/program"); <- Execution of module that initiates application
  • 68. Modules Webmake • modules-webmake can be used both from shell and programmatically - we can bind it to http server in Node.js and generate files on demand
  • 69. Modules Webmake • modules-webmake can be used both from shell and programmatically - we can bind it to http server in Node.js and generate files on demand • Dependencies are parsed statically, it introduces some limitations, for specific cases we may force inclusion of chosen modules with ‘include’ option.
  • 70. Modules Webmake • modules-webmake can be used both from shell and programmatically - we can bind it to http server in Node.js and generate files on demand • Dependencies are parsed statically, it introduces some limitations, for specific cases we may force inclusion of chosen modules with ‘include’ option. • modules-webmake reads local dependencies and those from external packages, one limitation is that it doesn’t recognize two different versions of same package (it will be addressed)
  • 71. Modules Webmake • modules-webmake can be used both from shell and programmatically - we can bind it to http server in Node.js and generate files on demand • Dependencies are parsed statically, it introduces some limitations, for specific cases we may force inclusion of chosen modules with ‘include’ option. • modules-webmake reads local dependencies and those from external packages, one limitation is that it doesn’t recognize two different versions of same package (it will be addressed) • Up to date documentation can be found at github project page: https://github.com/medikoo/modules-webmake
  • 72. Modules Webmake Last week I finished work on application that was built with help of modules-webmake. • It’s HTML5 application, targetted only for modern browsers (newest FF, Chrome and Safari (both OSX & iOS)) • To support Offline mode we needed to put whole application logic to client side, including templates and simple database engine. • Node.js on server-side, takes care about clients synchronization and saving data to physical database (mongodb) • Minimalistic client-server communication based on sockets (Socket.IO)
  • 73. Modules Webmake Final JavaScript file for client consists of 273 modules from 19 packages. 176 of mentioned modules works also on server side. It means that about 60% of client-side code is also running on server-side. Concatenated file is 11 thousand lines long and weights about 370kB before minification and zipping. It looks quite promising, if we take into account, that it consists of templates for whole application and all other modules that application is made of, including simple database engine. After application load, all client-server communication is minimal as all pages as generated by client.
  • 75. Modules Webmake Upcoming improvements: • Not only parser, but full modules engine. What for? It will allow to run and test modules with it’s dependencies in differently setup environments, like pure V8 + Modules, or emulation of browser environment.
  • 76. Modules Webmake Upcoming improvements: • Not only parser, but full modules engine. What for? It will allow to run and test modules with it’s dependencies in differently setup environments, like pure V8 + Modules, or emulation of browser environment. • Work in a background, it will allow much more optimized and faster file generation (watching file system for changes, immediate serving of generated files when integrated with node.js http server)
  • 77. Modules Webmake Upcoming improvements: • Not only parser, but full modules engine. What for? It will allow to run and test modules with it’s dependencies in differently setup environments, like pure V8 + Modules, or emulation of browser environment. • Work in a background, it will allow much more optimized and faster file generation (watching file system for changes, immediate serving of generated files when integrated with node.js http server) • Optional minification, compilation
  • 78. Modules Webmake Upcoming improvements: • Not only parser, but full modules engine. What for? It will allow to run and test modules with it’s dependencies in differently setup environments, like pure V8 + Modules, or emulation of browser environment. • Work in a background, it will allow much more optimized and faster file generation (watching file system for changes, immediate serving of generated files when integrated with node.js http server) • Optional minification, compilation • Discovering modules that were required but not used
  • 79. Modules Webmake Upcoming improvements: • Not only parser, but full modules engine. What for? It will allow to run and test modules with it’s dependencies in differently setup environments, like pure V8 + Modules, or emulation of browser environment. • Work in a background, it will allow much more optimized and faster file generation (watching file system for changes, immediate serving of generated files when integrated with node.js http server) • Optional minification, compilation • Discovering modules that were required but not used • Splitting into few files (for faster client-side load)
  • 80. Modules Webmake Upcoming improvements: • Not only parser, but full modules engine. What for? It will allow to run and test modules with it’s dependencies in differently setup environments, like pure V8 + Modules, or emulation of browser environment. • Work in a background, it will allow much more optimized and faster file generation (watching file system for changes, immediate serving of generated files when integrated with node.js http server) • Optional minification, compilation • Discovering modules that were required but not used • Splitting into few files (for faster client-side load) • Modules should not be duplicated in different files, introduction of intelligent more than one file generation
  • 81. Modules Webmake Upcoming improvements: • Not only parser, but full modules engine. What for? It will allow to run and test modules with it’s dependencies in differently setup environments, like pure V8 + Modules, or emulation of browser environment. • Work in a background, it will allow much more optimized and faster file generation (watching file system for changes, immediate serving of generated files when integrated with node.js http server) • Optional minification, compilation • Discovering modules that were required but not used • Splitting into few files (for faster client-side load) • Modules should not be duplicated in different files, introduction of intelligent more than one file generation • Small code fixes for buggy engines e.g. quoting reserved keywords used as property names
  • 82. Future: Harmony We will have modules natively in JavaScript http://wiki.ecmascript.org/doku.php?id=harmony:modules_examples
  • 83. Future: Harmony We will have modules natively in JavaScript http://wiki.ecmascript.org/doku.php?id=harmony:modules_examples Base concept of Harmony Modules is same as in CommonJS Modules.
  • 84. Future: Harmony We will have modules natively in JavaScript http://wiki.ecmascript.org/doku.php?id=harmony:modules_examples Base concept of Harmony Modules is same as in CommonJS Modules. Differences lies in dedicated syntax, and powerful optional features like dynamic loading, possibility to load external modules via url etc.
  • 86. Harmony Modules What we currently write for Node.js: add.js module.exports = function() { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) sum += args[i++]; return sum; }; increment.js var add = require('./add'); module.exports = function(val) { return add(val, 1); }; program.js var inc = require('./increment'); var a = 1; inc(a); // 2
  • 87. Harmony Modules Will be written that way with Harmony: add.js export function add () { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) sum += args[i++]; return sum; }; increment.js import add from './add'; export function increment (val) { return add(val, 1); }; program.js import { increment: inc } from './increment'; var a = 1; inc(a); // 2
  • 88. Harmony Modules Modules Webmake for EcmaScript 3/5: (function (modules) { // 53 lines of import/export logic }) ({ "root": { "add.js": function (exports, module, require) { module.exports = function () { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) sum += args[i++]; return sum; }; }, "increment.js": function (exports, module, require) { var add = require('./add'); module.exports = function (val) { return add(val, 1); }; }, "program.js": function (exports, module, require) { var inc = require('./increment'); var a = 1; inc(a); // 2 } } }) ("root/program");
  • 89. Harmony Modules Modules Webmake for Harmony: module add { export function add () { var sum = 0, i = 0, args = arguments, l = args.length; while (i < l) sum += args[i++]; return sum; }; }; module increment { import add from add; export function increment (val) { return add(val, 1); }; }; module program { import { increment: inc } from increment; var a = 1; inc(a); // 2 }; import * from program;
  • 90. Server & Browser If you use CommonJS/Node.js Modules today, it won’t be problematic for you to switch to Harmony in few years time
  • 91. Server & Browser If you use CommonJS/Node.js Modules today, it won’t be problematic for you to switch to Harmony in few years time Today: CommonJS/Node.js Modules & modules-webmake
  • 92. Server & Browser If you use CommonJS/Node.js Modules today, it won’t be problematic for you to switch to Harmony in few years time Today: CommonJS/Node.js Modules & modules-webmake Tomorrow: Harmony Modules
  • 93. Server & Browser If you use CommonJS/Node.js Modules today, it won’t be problematic for you to switch to Harmony in few years time Today: CommonJS/Node.js Modules & modules-webmake Tomorrow: Harmony Modules (& modules-webmake ?)
  • 95. Thank You ! Mariusz Nowak mariusz@medikoo.com @medikoo github.com/medikoo