Skip to content

Instantly share code, notes, and snippets.

@nikku
Last active March 9, 2016 12:19
Show Gist options
  • Save nikku/ad6dbb202ce2b735c905 to your computer and use it in GitHub Desktop.
Save nikku/ad6dbb202ce2b735c905 to your computer and use it in GitHub Desktop.
browserify-requirejs-non-hating-comparison

RequireJS / Browserify: A non-hating Comparison

This post attempts to compare RequireJS/AMD with Browserify/CommonJS as packaging and modularization approaches for modern web applications.

Look and Feel

A CommonJS/Browserify module

Modules are built according to the CommonJS pattern and work in both NodeJS and the browser. They export their dependencies through the module.exports key.

var fs = require('fs');

var angular = require('angular'),
    otherservice = require('./otherservice');


var ngModule = angular.module('my.module');

var template = fs.readFileSync(__dirname + '/template.html', 'utf-8');

ngModule.directive('myDirective', function() {
  return {
    template: template
  };
});

module.exports = ngModule;

A RequireJS/AMD module

Modules are built according to the asynchronous module definition pattern and wrapped in a require/define callback that returns the module export.

define([ 'angular', './otherservice', 'text!./template.html' ], function(angular, otherservice, template) {

  var ngModule = angular.module('my.module');
  
  ngModule.directive('myDirective', function() {
    return {
      template: template
    };
  });

  return ngModule;
});

Optionally you can use a CommonJS like require('dependency') syntactic sugar.

define(['require', 'angular', './otherservice', 'text!./template.html' ], function(require) {

  var angular = require('angular'),
      otherservice = require('./otherservice');
  
  
  var ngModule = angular.module('my.module');
  
  var template = require('text!./template.html');
  
  ngModule.directive('myDirective', function() {
    return {
      template: template
    };
  });
  
  return ngModule;
});

Comparison Table

The following table compares multiple aspects of each approach.

aspect RequireJS + AMD Browserify + CommonJS
loading async (default), sync (after minification) sync (after processing)
preprocessing optional mandatory (creates browser compatible file)
dependency declaration via require#config package.json
transitive external dependencies must be declared in global config automatically managed
project packaging n/a, user defined npm
module definition AMD, define([ ... ], function() { } CommonJS, module.exports = ...
async loading yes no
minifies to single / multiple files, AMD/UMD single / multiple files, require stub (default), global object, UMD
resource inlining / preprocessing loader plug-ins, e.g. text transforms, e.g. brfs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment