Thursday, January 14, 2016

scaffold to make js library support amd and commonjs

Here is the scaffold using IIFE (Immediately-Invoked Function Expression):
(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 {
    root.myModule = factory(root.postal);
  }
}(this, function(postal) {
  // module code here....

  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;
}));
Here is the reference blog:
http://ifandelse.com/its-not-hard-making-your-library-support-amd-and-commonjs/

No comments:

Post a Comment