4

I have created a javascript library which adds only one global object to the global space.

The global object happens to be a function and the name of the function matches the name of the file.

This is how it looks:

filename: myfunction.js

code:

myfunction = function() {
   ...
};

How do I make my library compliant with amd and require.js ?

Zo72
  • 14,593
  • 17
  • 71
  • 103

2 Answers2

10

The Requirejs Docs tell you all about how to make an AMD compliant module. However, information on how to keep a module working when used without AMD (<script> tag) is hard to find there. Anyway, when in a Requrirejs context, the "define" method is defined. Otherwise, the example below just uses window.x (not the most elegant solution) to expose the function to the global space from within a closure.

(function (module) {
    if (typeof define === "function" && define.amd) {
        define(function () { return module; });
    } else {
        window.myfunction = module.myfunction;
    }
}({
    myfunction: function () {
        /* ... */
    }
}));

See also: https://stackoverflow.com/a/14033636

Community
  • 1
  • 1
depoulo
  • 355
  • 2
  • 10
1

I have found a great post that explains the whole process.

http://ifandelse.com/its-not-hard-making-your-library-support-amd-and-commonjs/

In a nutshell, the author suggested the following pattern :

** Here, postal.js is a AMD/Commonjs compliant module.

(function (root, factory) {

if(typeof define === "function" && define.amd) {
// Now we're wrapping the factory and assigning the return
// value to the root (window) and returning it as well to
// the AMD loader.
define(["postal"], function(postal){
  return (root.myModule = factory(postal));
});
} else if(typeof module === "object" && module.exports) { 
// I've not encountered a need for this yet, since I haven't
// run into a scenario where plain modules depend on CommonJS
// *and* I happen to be loading in a CJS browser environment
// but I'm including it for the sake of being thorough
module.exports = (root.myModule = factory(require("postal")));
} 
else {   //node.js diverges from the CommonJS spec a bit by using module.  So, to use it in other common js environments
root.myModule = factory(root.postal);}}(this, function(postal) {//passing this as the root argument, and our module method from earlier as the factory argument. If we run this in the browser, this, will be the window.

 var sub;
   var ch = postal.channel("myModule");
   var myModule = {
     sayHi:function() {
            ch.publish("hey.yall", { msg: "myModule sez hai" });
     },
     dispose: function() {
            sub.unsubscribe();
     }};return myModule;}));
sudip
  • 2,781
  • 1
  • 29
  • 41