Skip to content

AMDClean for Web Apps

Compare
Choose a tag to compare
@gfranko gfranko released this 26 Jan 20:32
· 166 commits to master since this release

With the 0.6.0 release, AMDClean can now be reliably used to replace Almond.js in your web apps. Here are the changes that make this possible:

Converting Third-Party Libraries

Let's use jQuery as an example. In the jQuery source code, there is the following conditional AMD check to see if an AMD loader is being used:

// jQuery Source
if ( typeof define === "function" && define.amd ) {
    define( "jquery", [], function() {
        return jQuery;
    });
}

AMDClean will now transform the jQuery source to this:

if ( true ) {
var jquery = function () {
        return jQuery;
    }();
}

Before version 0.6.0, AMDClean would have left the AMD conditional if statement alone, and would not know the return value for the jquery module (causing a syntax error in your web app).

Correctly Transforming Define() Methods That Assume CommonJS support

Let's use the Esprima library as an example. Esprima uses the following syntax to conditionally check to see if an AMD loader is being used:

// Esprima Source
(function (root, factory) {
    'use strict';

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // Rhino, and plain browser loading.
    if (typeof define === 'function' && define.amd) {
        define(['exports'], factory);
    } else if (typeof exports !== 'undefined') {
        factory(exports);
    } else {
        factory((root.esprima = {}));
    }
}(this, function (exports) {
  // Esprima source code
  // ...
  // Does not return anything
}));

In the above code example, Esprima is conditionally defining an anonymous AMD module by passing the function identifier, factory.

The factory function that is being passed does not return any value inside of its function body, and instead just assigns properties to its exports argument. It does this since it expects Require.js to automatically understand that it is using CommonJS syntax and to return the exports argument as the module return value.

With the 0.6.0 release, AMDClean is now smart enough to correctly transform this conditional AMD definition. Here is how AMDClean now transforms the above code:

(function (root, factory) {
    'use strict';

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // Rhino, and plain browser loading.
    if (true) {
      var esprima = function (module) {
        return factory();
    }({});
    } else if (typeof exports !== 'undefined') {
        factory(exports);
    } else {
        factory((root.esprima = {}));
    }
}(this, function (exports) {
  exports = exports || {};
  // Esprima source code
  // ...
  // Returns exports
  return exports;
}));