Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapper to allow a module to work with AMD/CommonJs or script tags?

I just took a shot at wrapping one of our modules that is meant to be included via a <script> tag in some boilerplate to allow optional AMD loading with requirejs.

It was quite painful and the best I could come up with is:

(function(){
var exports, jQuery;
if (typeof window.define === 'function' && typeof window.requirejs === 'function') {
    exports     = {};
    define(['jquery'], function (jq) {
        jQuery = jq;
        return thisModule();
    });
} else {
    exports     = window;
    jQuery      = window.jQuery;
    thisModule();
}


function thisModule() {
}

})();

Notice that this is

  • A LOT of boilerplate
  • Requires you to declare dependencies in variables (only jQuery in this case thankfully) AND amd
  • Needs yet more code if I want to have CommonJs support.

I am primarily concerned about the second point as that one is going to be a doozy when I get beyond wrapping our core files. I'm sure there's some neat(er) wrapper implementations out there but I can't find any.

Anyone have any tips?

like image 550
George Mauer Avatar asked Feb 06 '13 18:02

George Mauer


People also ask

What is CommonJS and AMD?

AMD and CommonJS are both Javascript module loader. They accomplish the same task but works different. AMD is better for browser, hence, the name 'Asynchronous', as it loads each distinct module in async manner instead of loading in one large file. No extra steps are required to use AMD, it works out-of-the-box.

What is AMD script?

Asynchronous module definition (AMD) is a specification for the programming language JavaScript. It defines an application programming interface (API) that defines code modules and their dependencies, and loads them asynchronously if desired.

What is CommonJS and RequireJS?

RequireJS implements the AMD API (source). CommonJS is a way of defining modules with the help of an exports object, that defines the module contents. Simply put, a CommonJS implementation might work like this: // someModule. js exports.


1 Answers

What you are trying to re-create something that already exists, I did exactly the same thing, coming up with a slightly different solution in my StackOverflow question.

To cut a long story short the name you need to know is "Universal Module Definition" and there's a GitHub located at https://github.com/umdjs/umd with a variety of different implementations.

like image 120
Forbesmyester Avatar answered Sep 29 '22 01:09

Forbesmyester