Search code examples
node.jsrequirejsglobalamdcommonjs

Define module with dependencies for AMD (requirejs) and Common.js (Node.js) and global scope


I'm trying to create a function that accessible with AMD, Common.js, and in the Global Scope. My one caveat is that it has dependancies. Require.js and global scope seem to be working fine but I can't get the dependencies to load in Node.js.

(function(global, factory) {
  // Node.js
  if (typeof exports === 'object' && typeof module !== 'undefined') {
    moment = require('moment');
    return module.exports = factory();

  }
  // require.js
  else if (typeof define === 'function' && define.amd) {
    return define(['moment'], function(moment) {
      global.moment = moment;
      return factory();
    });
  }
  // global
  else {
    return global.formatDate = factory();
  }
})(this, function() {

  var formatDate = function(date, format) {
    if (typeof moment !== 'function' && !moment) {
      console.error('moment is required to format date')
      return date;
    }
   return moment(date).format(format);
  };

  return formatDate;
});

Solution

  • Instead of exposing dependencies as globals, pass them as arguments to your factory.

    For example:

    (function (root, factory) {
        if (typeof define === 'function' && define.amd) {
            define([ 'module', 'moment' ], function (module, moment) {
                module.exports = factory(moment);
            });
        } else if (typeof module === 'object') {
            module.exports = factory(require('moment'));
        } else {
            root.formatDate = factory(root.moment);
        }
    }(this, function (moment) {
    
    }));
    

    Check out the Universal Module Definition (UMD) recipes at https://github.com/umdjs/umd