Search code examples
javascriptrequirejsmodularitycommonjsjs-amd

Making requirejs modules AMD compliant


I'm currently building an app where the frontend is doing a lot of the heavy lifting. To keep everything neat and organised I'd like to use requirejs. However, to use require.js to its' full extent all the modules I use should be AMD compliant.

Which means that every time a module that I use is updated I need to either wait for an AMD-compliant version to appear or make one myself ( Which I currently don't know how to ).

This is a real turnoff.

Looking at this https://github.com/jrburke/backbone/blob/optamd/backbone.js it seems to me that making a module like Backbone AMD-compliant isn't as straightforward as wrapping the plugin into a generic function.

Is there a more or less straightforward way of making a module AMD-compliant?


Solution

  • Well his version is pretty bullet-proofed so it'll run under a variety of circumstances. Since you know the environment you are running in and what is available/what isn't then you can make some assumptions that will let you do something that is much more straightforward.

    Check out this gist where I make bacbkonejs an AMD module assuming jQuery, underscore and define are in the global scope and I don't need commonjs support: https://gist.github.com/2762813

    I just add

    define(function() {
      var obj = {};
      obj._ = window._;
      obj.jQuery = window.jQuery;
    

    to the top and

    .call(obj);
       return obj.Backbone;
    });
    

    to the bottom.


    Thanks to @SimonSmith for bringing UseJS to my attention. UseJS is an AMD loader plugin that will allow you to load non-amd formatted modules without modifying them. I haven't used use myself yet but it looks promising: https://github.com/tbranyen/use.js/

    UPDATE

    RequireJS 2.0 now directly supports the functionality you are looking for via shim configs: https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.0#wiki-shim