#111·umd

AMD using require sugar syntax

Author: dagossCreated Jun 16, 2017Updated Jun 16, 2017

RequireJS allows some syntatic sugar so that instead of passing an array of dependencies, then declaring names for those dependencies in the factory in (hopefully) the correct order, you just class require, and then can use more familiar (to CommonJS people) require() calls:

javascript
define(function(require){
  var $ = require('jquery')
  var utilities = require('../app/utilities')
  // insert magic words here that make browser do things
})

To do this in a UMD friendly way, I think you'd do something like this:

javascript
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(factory)
  } else {
    // Browser
    root.returnExports = factory()
  }
}(this, function (require) {
  if (typeof require === 'function' && define.amd){
    var $ = require('jquery')
  }
  // insert more magic words here
  return {}
}));

I don't know how prevalent this type is, but I find it much easier to write and read. Maybe this example could be covered?