michaelficarra / commonjs-everywhere

:rainbow: minimal CommonJS browser bundler with aliasing, extensibility, and source maps
BSD 3-Clause "New" or "Revised" License
158 stars 21 forks source link

add amd support through --amd flag #91

Closed michaelficarra closed 10 years ago

michaelficarra commented 10 years ago

When --amd is given, we should output a wrapper like this:

(function(root, factory) {
  if (typeof define === 'function' && define.amd)
    define('moduleName', [], factory);
    /* or, if -x was not provided,
    define([], factory);
    */
  else if (typeof exports === 'object')
    module.exports = factory();
  else
    root.moduleName = factory();
    /* or, if -x was not provided,
    factory();
    */
}(this, function() {
  // ...
  return require('mainModule');
}));

(adapted from umdjs/umd)

Requested by @Constellation in https://github.com/Constellation/escodegen/issues/115

arcanis commented 10 years ago

root.moduleName should be always exported, even if the module is also exported as a module :(

Also, I don't think it's a Cjs-Everywhere issue (see my comment on Constellation/escodegen#115).

michaelficarra commented 10 years ago

Okay, how about this?

(function(root, factory) {
  if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    if (typeof define === 'function' && define.amd)
      define('moduleName', [], factory);
    root.moduleName = factory();
    /* or, if -x was not provided,
    if (typeof define === 'function' && define.amd)
      define([], factory);
    factory();
    */
  }
}(this, function() {
  // ...
  return require('mainModule');
}));
arcanis commented 10 years ago

There is an issue in a Require.js context : the factory will be called twice. With a bit more code :

(function(root, factory) {
  if (typeof exports === 'object') {
    module.exports = factory();
  } else {

    var instance = root.moduleName = factory();
    if (typeof define === 'function' && define.amd) {
      define('moduleName', [], function () { return instance; });
    }

    /* or, if -x was not provided,
    var instance = factory();
    if (typeof define === 'function' && define.amd) {
      define([], function () { return instance; });
    }
    */

  }
}(this, function() {
  // ...
  return require('mainModule');
}));
michaelficarra commented 10 years ago

Okay, that works for me.