Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an AMD module for use in pages without RequireJS?

I need to re-structure an existing AMD module to make it both usable by pages with/without RequireJS presented. How should I do it, and is there any example code? Preferably, it would be a way without polluting the global namespace, though not a strict requirement.

like image 349
gsklee Avatar asked Sep 24 '12 03:09

gsklee


People also ask

How do you define an AMD module?

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 the difference between RequireJS CommonJS and AMD loaders?

RequireJS is probably the most popular implementation of AMD. One major difference from CommonJS is that AMD specifies that modules are loaded asynchronously - that means modules are loaded in parallel, as opposed to blocking the execution by waiting for a load to finish.

Why do we need RequireJS?

RequireJS is a basic loader, which is used to loads the JavaScript files, it is a framework to manage dependencies between JavaScript files, and in modular programming, all the functionality divides in different modules, so RequireJs is a best tool to assemble different JavaScript files from different modules by which ...

What is AMD RequireJS?

RequireJS syntax allows to load modules faster without worrying about keeping track of the order of dependencies. You can load multiple versions of the same module in the same page.


1 Answers

This is not a bad idea at all, quite often JS libs are required to support a AMD/non AMD environment. Here is one variation of the solution:

!function (name, definition) {
    if (typeof module != 'undefined') module.exports = definition()
    else if (typeof define == 'function' && define.amd) define(name, definition)
    else this[name] = definition()
}('reqwest', function () {

    // Module here

});

The only downside is you can't request other dependencies, so this would only be useful in stand alone libraries, like the ones below

  • Dustin Diaz's Reqwest
  • Mustache
like image 87
Simon Smith Avatar answered Oct 05 '22 23:10

Simon Smith